<?php
namespace Home\Controller;
use Think\Controller;
use Think\Model;

static  $uploadfiles = array();


//public static $db1 = new Model("temp_info","tb_","mysql://root:r00t123@localhost:3306/tb"); //全局没成功。

class AppController extends Controller {
    //祈贝版本号
protected $qibeiversion=array(
    "1.0",
    "2.0",
    "2.1.1",
    "2.2",
    "2.3",
    "2.4",
    "2.4.1",
    "2.4.2",
    "2.4.3",
    "2.4.4",
    "2.4.5",
    "2.4.6",
    "2.4.7",
    "2.4.8",
    "2.4.9"
);
//祈贝版本号
protected $doctorqibeiversion=array(
    "1.0",
    "2.0",
    "2.1.1",
    "2.2",
    "2.3",
    "2.4",
    "2.4.1",
    "2.4.2",
    "2.4.3",
    "2.4.4",
    "2.4.5",
    "2.4.6",
    "2.4.7",
    "2.4.8",
    "2.4.9"
);
//主帐号
protected  $accountSid= 'aaf98f8952f255490152f3e8e70f04d0';

                //主帐号Token
protected   $accountToken= '5fc00f099f80497da40232d865e04abe';

                //应用Id
protected    $appId='aaf98f8952f255490152f3ed425d04f5';

                //请求地址，格式如下，不需要写https://
protected    $serverIP='sandboxapp.cloopen.com';

                //请求端口 
protected    $serverPort='8883';

                //REST版本号
protected   $softVersion='2013-12-26';
//public function mdd5()
//{
//	$doctor_ds = D('Doctor');
//	$xxxx = $doctor_ds->select();
//	foreach ($xxxx as  $k => $v)
//	{
//		$pass = md5($v['logname']);
//		$uid = $v['id'];
//		$result1 = $doctor_ds->where('id='.$uid)->setField('password', $pass);	
//	}
//}

//    //测试接口去掉医生
//    public function guolv(){
//        $doctor_ds = D('Doctor');
//        $xxxx = $doctor_ds->select();
//        foreach ($xxxx as  $k => $v)
//	{
//            
//            if (preg_match("/\s/", $v['img'])) {
//                $v['img'] = str_replace(' ', '', $v['img']);
//                $doctor_ds->where('id='.$v['id'])->setField('img', $v['img']);	
//            } else {
//                
//            } 
//	}
//    }
//    //测试接口去掉医生
//    public function guolvhos(){
//        $doctor_ds = D('Hospital');
//        $xxxx = $doctor_ds->select();
//        foreach ($xxxx as  $k => $v)
//	{
//            
//            if (preg_match("/\s/", $v['imgs'])) {
//                $v['imgs'] = str_replace(' ', '', $v['imgs']);
//                $doctor_ds->where('id='.$v['id'])->setField('imgs', $v['imgs']);	
//            } else {
//                
//            } 
//	}
//    }

//测试动作，m=Home&c=App&a=test
//    public function test(){ 
//    	//$result = array('result' => 0,'test' => 'haha');
//		$sql = "select * from tb_hospital limit 2";
//		//第一个参数：随便填一个真实的表名即可。
//		$db1 = new Model("temp_info","tb_","mysql://root:r00t123@localhost:3306/tb");//必须 use Think\Model;
//		$result = $db1->query($sql);
//    	$this->echoJson($result); 
//    } 
//    public function test2()
//	{
//		$sql = "select * from tb_hospital limit 3";
//		$db2 = M("hospital","tb_","mysql://root:r00t123@localhost:3306/tben");//不必 use Think\Model;
//		$result = $db2->query($sql);
//    	$this->echoJson($result); 
//    } 
//	
//    public function test3()
//	{ 
//	$vv = "a,b,c";
//	$Ext1arr = explode(",",$vv);//$Ext1arr[0] = 'a',  $Ext1arr[1] = 'b'
//	$this->echoJson( $Ext1arr[1] );
//	
//		//$sql = "select * from tb_hospital limit 3";
//		//$result = $this->db(1)->query($sql);//失败。
//    	//$this->echoJson($result); 
//    } 

	//==================================================================================
	/*
	>>功能: 消息机制心跳函数，病人版用。
	>>详细: 用户端APP定时器调用，每隔几秒调用此函数，获取需要处理的即时消息类型。
	>>示例: http://121.40.78.46/tb/index.php?m=Home&c=App&a=heartbeat_user&uid=5
	>>入参 uid: 用户id，int
	>>出参: msgid:消息编号。todo:消息名称,即需要app尽快调用的服务器接口名称
	2=myDoctorList,医生已确认用户的添加医生申请--病人端需要调用myDoctorList刷新,
	5=searchChatObj,有人在跟你聊天，需要刷新聊天列表。
	6=getA_Dct_Admission,医生接诊了你，请注意。
	*/
//	public function heartbeat_user()
//    {
//	    $userid    = intval(I('request.uid'));
//		$heartbeatmsg_ds = D('heartbeat_msgtable');
//		$time = time();//设个门槛条件
//		
//		$msgs = $heartbeatmsg_ds->where('uid='.$userid . ' and time<=' .$time)->select();
//		        $heartbeatmsg_ds->where('uid='.$userid . ' and time<=' .$time)->delete();
//    	foreach ($msgs as $k => $v){
//    		unset($msgs[$k]['uid']);  
//            unset($msgs[$k]['time']);
//            unset($msgs[$k]['timex']);  			
//    	}    	 
//    	//$this->echoJson($msgs);
//        $this->echoJson(array('result' => 0, 'msgs' => $msgs));		
//	
//	}	
//	/*
//    >>说明: 两个暂时代码一样。分开以便可以定时器不同。	
//	>>功能: 消息机制心跳函数，医生版用	
//	>>详细: 医生端APP定时器调用，获取需要处理的即时消息类型。
//	>>示例: http://121.40.78.46/tb/index.php?m=Home&c=App&a=heartbeat_doctor&uid=100000001
//	>>uid:医生id,int
//	>>出参: msgid:消息编号。todo:消息名称,即需要app尽快调用的服务器接口名称 	
//	1=Dct_NeedMyConfirmMyDoctor，医生端，有"添加医生申请"消息，需要医生确认。
//	3=Dct_getfinishedadvice，病人完成了一个作业，医生端需要刷新“候诊”页	
//	5=searchChatObj,有人在跟你聊天，需要刷新聊天列表。
//	*/
//	public function heartbeat_doctor()
//    {
//	    $userid    = intval(I('request.uid'));
//		$heartbeatmsg_ds = D('heartbeat_msgtable');
//		$time = time();//设个门槛条件
//		
//		$msgs = $heartbeatmsg_ds->where('uid='.$userid . ' and time<=' .$time)->select();
//		        $heartbeatmsg_ds->where('uid='.$userid . ' and time<=' .$time)->delete();
//    	
//    	foreach ($msgs as $k => $v){
//    		unset($msgs[$k]['uid']);  
//            unset($msgs[$k]['time']);  			
//    	}
//    	//$this->echoJson($msgs); 
//		$this->echoJson(array('result' => 0, 'msgs' => $msgs)); 								
//	}	
	 
	 
    //==========================================================================================
	//病人
	//http://121.40.78.46/tb/index.php?m=Home&c=App&a=register&name=xxx&telephone=1234567890a&password=xxx&captcha=验证码 
	//入参:name:病人的登录名，普通字符数字下划线，避免使用逗号分号空格斜杠这些特殊符号。
	//入参: telephone: 电话号码，11位数字，必须满11位。。
	//入参: password: 密码。避免使用逗号分号空格斜杠这些特殊符号。
	//入参: captcha :手机接收到的验证码
    public function register(){
    	$phone = I('request.telephone');
    	$password = I('request.password');
		$captcha = I('request.captcha');
		$temp_info = D('temp_info'); 
                if(!preg_match('/^[_0-9a-z]{8,16}$/i',$password)){
			$this->echoJson(array('result' => 1, 'info' => "密码只能是字母、数字、下划线长度至少8位"));
			exit;
		}
        $data['name']='ivfbb'.  substr(md5($phone),0,8);
    	$data['password'] = md5($password);
    	$data['telephone'] = $phone;
    	$data['register_time'] = time();
        $data['register_ip']=$this->getIP();
    	$user_ds = D('User');
    	$r = $user_ds->where("id<100000000")->order("id DESC")->limit(0,1)->find();
        $data['id'] = $r['id']+1;
    	
    	//telephone是否已经存在
    	$user = $user_ds->where("telephone='".$phone."'")->find();
    	if ($user !== null){
    		$this->echoJson(array('result' => 2, 'reason' => '用户手机号码已经存在'));			
    		exit;
    	} 
		
		

		$atta =  $temp_info->where('uid='. $phone)->order('expire_time desc')->limit(0,1)->find();
//print_r($atta);
		if( ($atta ==null ) || ($captcha <> $atta['attach']))
		{
    		$this->echoJson(array('result' => 3, 'reason' => '验证码错误'));			
    		exit;		
		}
		
		//if($phone != null && $phone !="")
		//{
		//$temp_info->where('uid='. $phone)->delete();
		//}
		
    
    	$user_id = $user_ds->add($data);
    	
    	if (!$user_id)		
		{
    		$this->echoJson(array('result' => 9, 'reason' => '数据保存到数据库失败'));
    	} else {
                
                
//                $REST=new \Org\Util\REST($this->serverIP,$this->serverPort,$this->softVersion);
//                $REST->setAccount($this->accountSid,$this->accountToken);
//                $REST->setAppId($this->appId);
//                $result = $REST->CreateSubAccount('ivf'.$phone);
//                if($result == NULL ) {
//                    $this->echoJson(array('result' => 10, 'reason' => '创建容联失败'));
//                    exit;
//                }
//                if($result->statusCode!=0) {
//                    $this->echoJson(array('result' => 10, 'reason' => '创建容联失败'));exit;
//                }else {
//                    $rl=D("Rl");
//                    // 获取返回信息
//                    $subaccount = $result->SubAccount;
//                    $data['subAccountid']=$subaccount->subAccountSid;
//                    $data['subToken']=$subaccount->subToken;
//                    $data['dateCreated']=$subaccount->dateCreated;
//                    $data['voipAccount']=$subaccount->voipAccount;
//                    $data['voipPwd']=$subaccount->voipPwd;
//                    $data['uid']=$user_id;
//                    $data['name']='ivf'.$phone;
//                    $rl->add($data);
//                } 
    		$this->echoJson(array('result' => 0, 'userid' => intval($user_id)));
    	}
    }
    /**
     * //获取客户端ip地址
     * @return string
     */
    private function getIP()
    {
        if (getenv("HTTP_CLIENT_IP"))
        {
            $ip = getenv("HTTP_CLIENT_IP");
        }
        else
        {
            if (getenv("HTTP_X_FORWARDED_FOR"))
            {
                $ip = getenv("HTTP_X_FORWARDED_FOR");
            }
            else
            {
                if (getenv("REMOTE_ADDR"))
                {
                    $ip = getenv("REMOTE_ADDR");
                }
                else
                {
                    $ip = "Unknow";
                }
            }
        }

        return $ip;
    }
    //==========================================================================================
	//登录
	//http://121.40.78.46/tb/index.php?m=Home&c=App&a=login&logtype=yyy&name=xxx&telephone=1234567890a&password=xxx
    //三个参数中，name和telephone可选其一。
    //logtype :	doctor
    public function login()
	{/*
    	$userdct = I('logtype', '');		
		$logname = I('name', '');
    	$phone = I('telephone', '');
    	$password = md5(I('password'));
		*/
		
    	$userdct = I('request.logtype', '');		
		$logname = I('request.name', '');
    	$phone = I('request.telephone', '');
    	$password = md5(I('request.password'));		
/*	
$myfilex = fopen("qq-login.txt", "w") or die("Unable to open file!");	
fwrite($myfilex, "\nlogname=" . $logname );

    			
		$postlognamex = I('post.name', '');		
fwrite($myfilex, "\npostlognamex=" . $postlognamex); 	 
 	
		$getlognamex = I('get.name', '');
		fwrite($myfilex, "\ngetlognamex=" . $getlognamex);
		
		$requestname = I('request.name', '');
		fwrite($myfilex, "\nrequestname=" . $requestname);
		
fclose($myfilex);
//*/
		
    	$doctor_ds = D('Doctor');
		$user_ds = D('User');
		
    	if ($logname == '' and $phone == ''){
    		$this->echoJson(array('result' => 1, 'reason' => '用户名和手机号都为空'));
    		exit;
    	}
		
    	if($userdct == 'doctor')
		{
			if ($logname !== '')
				$user = $doctor_ds->where("logname='".$logname."' AND password='".$password."'")->find();
			else if ($phone !== '')
				$user = $doctor_ds->where("telephone='".$phone."' AND password='".$password."'")->find();
			
			if ($user == null){
				$this->echoJson(array('result' => 1, 'reason' => '用户名或密码错误'));
				exit;
			}
			
			$logname = $user['logname'];
			$truename = $user['name'];
//                        ///朋友圈接口增加为了方便
//                        $r = $user_ds->where("id=".$user['id'])->find();
//                        if(!$r){
//                            $opt['id']=$user['id'];
//                            $opt['name']=$user['name'];
//                            $opt['telephone']=$user['telephone'];
//                            $opt['image']=$user['img'];
//                            $opt['birthday']=$user['birthday'];
//                            $opt['sex']=$user['sex'];
//                            $rr = $user_ds->add($opt);
//                            
//                        }
			
		}
		else
		{
			if ($phone !== '')
				$user = $user_ds->where("telephone='".$phone."' AND password='".$password."'")->find();
			
			if ($user == null){
				$this->echoJson(array('result' => 1, 'reason' => '用户名或密码错误'));
				exit;
			}	
			$logname = $user['name'];
			$truename = $user['truename'];			
		}

    	
    	$tag = substr(md5(time().mt_rand(0,1000)), 10, 20);
    	$login_time = time();
    	$expired_time = $login_time + 24*60*60;//一天过期
		
		
    	
    	$user_behavior_ds = D('UserBehavior');
    	$user_login_ds = D('UserLogin');//竟然能用??
    	$data['uid'] = $user['id'];
    	$data['login_time'] = $login_time;
    	$data['login_tag'] = $tag; //qq一次登录的标识，相当于sessionid
    	$data['expired_time'] = $expired_time;
    	$data['behavior'] = 'login';
    	$data['action_time'] = $login_time;
    	
    	$user_behavior_ds->startTrans();
			$user_login_info = $user_login_ds->where('uid='.$user['id'])->find();
			if ($user_login_info == null)
				$login_result = $user_login_ds->add($data);
			else
				$login_result = $user_login_ds->where('uid='.$user['id'])->save($data);
			$log_result = $user_behavior_ds->add($data);
			 
			if (!$login_result or !$log_result){
				$user_behavior_ds->rollback();
				$this->echoJson(array('result' => 1, 'reason' => '用户登录信息保存数据库失败'));
				exit;
			}
    	$user_behavior_ds->commit();
        if($user['image']!=null){
            $image="http://img.user.ivf-bb.com/" .$user['image'];
        }else{
            $image=null;
        }
    	$result = array(
    		'result' => 0,
    		'userid' => $user['id'],
            'phone' => $user['telephone'],
			'logname' => $logname,
			'truename' => $truename,
    		'tag' => $tag,
    		'expired_time' => $expired_time *1000,
			'image' => $image);
    	$this->echoJson($result);
    }
    //==========================================================================================
	//界面中未用到。
    //搜索医院 或 医生 ，如果有 name，则按name搜 医院和医生 ，如果没有name，则医院和医生各8个人气最高者。	
    //http://121.40.78.46/tb/index.php?m=Home&c=App&a=searchName&name=xxx
	//name: 医院 或 医生名，普通字符，
    public function searchName(){
    	$name = I('request.name', '');// 
    	
    	$doctor_ds = D('Doctor');
    	$hospital_ds = D('Hospital');
    	
    	//8个
    	$name == '' ? $hospital = $hospital_ds->order("renqi_cnt DESC")->limit(8)->select()
    	            : $hospital = $hospital_ds->where("name LIKE '%".$name."%'")
	    							->order("renqi_cnt DESC")->limit(8)->select();
									
    	$name == '' ? $doctor = $doctor_ds->where("auth_status=2")->order("renqi_cnt DESC")->limit(8)->select()
    	            : $doctor = $doctor_ds->where("auth_status=2 and name LIKE '%".$name."%'")
	    							->order("renqi_cnt DESC")->limit(8)->select();
    	$mach = array();
    	foreach ($hospital as $k => $v){
    		$mach[] = array('id' => intval($v['id']), 
    				'name' => $v['name'], 
    				'type' => 1); //hospital
    	}
    	
    	foreach ($doctor as $k => $v){
    		$mach[] = array('id' => intval($v['id']), 
    				'name' => $v['name'], 
    				'type' => 2); //doctor
    	}
    	
    	$this->echoJson(array('result' => 0, 'match' => $mach));
    }
    //搜索医生
    public function SearchDoctor($doc=''){
        $doctor_ds = D('Doctor');
        if($doc!=''){
           $res = $doctor_ds->where("auth_status=2 and name LIKE '%".$doc."%'")->select();
           foreach ($res as &$v){
                if($v['img']!=null){
                    $v['img']='http://img.cndoc.ivf-bb.com/'.$v['img'];
                }
                unset($v['logname']);
                unset($v['password']);
//                $doctor[] = array('id' => intval($v['id']), 'name' => $v['name'],'img'=>$v['img'],'cn_des'=>$v['abstract'],'en_des'=>$v['descrip']);
            }
           $this->echoJson(array('result' => 0, 'doctor' => $res));exit;
        }
        $this->echoJson(array('result' => 1, 'info' => "系统错误"));exit;
    }
    //==========================================================================================
    //通用接口，查询医院或医生详细信息
    //http://121.40.78.46/tb/index.php?m=Home&c=App&a=getDetail&type=2&id=100000001&userid=5	
	//type:int,1--医院，否则--医生。
	//userid, 查询者的id
	//id:int,医院或医生的id
    public function getDetail(){
    	$type = intval(I('request.type'));
    	$id = intval(I('request.id'));
		$userid = intval(I('request.userid'));
 
    	$doctor_ds = D('Doctor');
    	$hospital_ds = D('Hospital');
		$attention_doctor_ds = D('attention_doctor');
		$user_ds=D("User");
    	
    	if($type == 1) //医院
		{
		    $hospital_ds->where('id='.$id)->setInc('renqi_cnt', 1); //暂无意义，所以不弄人气表
			$hospital = $hospital_ds->where('id='.$id)->find();
		}
		else //医生
		{
		    $doctor = $doctor_ds->where('id='.$id)->find();
			//每个病人，不管查看多少次这个医生，只提供一个人气贡献。
			$doc_renqi_ds = D('doc_renqi'); 
			$looked = $doc_renqi_ds->where('userid='.$userid . ' and doctorid=' . $id)->find();
			if($looked == null)
			{
				$data['userid'] = $userid;
				$data['doctorid'] = $id;
				$data['time'] = time();
				$doc_renqi_ds->add($data);
				$doctor_ds->where('id='.$id)->setInc('renqi_cnt', 1);
			}	
		
		}
			   

    	
    	if ($type == 1){
    		unset($hospital['renqi_cnt']);
    		$hospital['id'] = intval($hospital['id']);
    	}
    	
    	if ($type == 2) //医生
		{
	    	$hh = $hospital_ds->where('id='.$doctor['hospital_id'])->find(); 
	    	$hh == null ? $doctor['hospital_name'] = '' 
	    			    : $doctor['hospital_name'] = $hh['name'];
	    	$doctor['id'] = intval($doctor['id']);
                if($doctor['img']!=null){
                        $doctor['img']='http://img.cndoc.ivf-bb.com/'.$doctor['img'];
                    
                }
	    	//unset($doctor['renqi_cnt']);
	    	unset($doctor['hospital_id']);
		unset($doctor['password']);	
			$attentionR = $attention_doctor_ds->where('userid='.$userid . ' and doctorid=' . $id)->find();
			if($attentionR == null)
			{	
			    $doctor['attention'] = '0';
                        }				
			else
			{
			    $doctor['attention'] = '1';
			}
			
			$my_doctor_ds = D('my_doctor');
			$mydoctorR = $my_doctor_ds->where('userid='.$userid . ' and doctorid=' . $id)->find();
			if($mydoctorR == null)
			{	
			    $doctor['mydoctor'] = '0';
                        }				
			else
			{
			    $doctor['mydoctor'] = '1';
			}	

			//是否好友
			if($id > 100000000)
			{
				$rec=$user_ds->where('id='.$userid)->getField("good_ids");
				
				
				$doctor['good_ids']=0;
				$recarr = explode(",",$rec);
				foreach ($recarr as $hy){
				    if($hy == $id)
					{
					    $doctor['good_ids']=1;
						break;
					}
				}					

			}			
    	}
    	
    	$type == 1 ? $this->echoJson(array('result' => 0, 'detail' => $hospital))
    			   : $this->echoJson(array('result' => 0, 'detail' => $doctor));
    }
    //==========================================================================================
    //根据国家，查找省份
    //http://121.40.78.46/tb/index.php?m=Home&c=App&a=getProvince&country=中国	
	//country: 以数字:  0为中国，1为美国. //如果为汉字，暂也可
    public function getProvince(){
    	$country = I('request.country');//如果为汉字，暂也可
		if($country == 0) {$country ='中国';}
		if($country == 1) {$country ='美国';}
                if($country == 2) {$country ='泰国';}
    	
    	$hospital_ds = D('Hospital');
    	//$hospital = $hospital_ds->where("country='".$country."'")->select();
		$hospital = $hospital_ds->where("country='".$country."'")->Distinct(true)->field('zid')->select();
//$province_ds = D('province'); 		
                
    	$province = array();
    	foreach ($hospital as $k => $v){
            $state=D("State");
            $rr=$state->where("id='".$v['zid']."'")->find();
    		$province[] = array('id'=>$v['zid'],'province' => $rr['name'],'province_en' => $rr['en_name']);
//$data['countryid']= 0;	
//$data['provinceid']= $k;
//$data['provincename']= $v['province'];	
//$province_ds->add($data);			
    	}
    	$this->echoJson(array('result' => 0, 'area' => $province));
    }    
    //==========================================================================================
    //国家+省市==>医院
	//http://121.40.78.46/tb/index.php?m=Home&c=App&a=getHospital&country=中国&province=上海
	//country: 以数字:  0为中国，1为美国. //如果为汉字，暂也可
    public function getHospital(){
    	$country = I('request.country');//国家
		if($country == 0) {$country ='中国';}
		if($country == 1) {$country ='美国';}
		if($country == 2) {$country ='泰国';}
    	$province = I('request.province');//省
//		    $province_ds = D('province');
//			$proRec = $province_ds->where("provinceid=".$province)->find();
//			if($proRec != null)
//			{
//			    $province = $proRec[provincename];
//			}
  	 
    	$hospital_ds = D('Hospital');
    	$hospital = $hospital_ds->where("zid='".$province."'")->select();
    	$result = array();
    	foreach ($hospital as $k => $v){
    		$result[] = array('id' => intval($v['id']),'name' => $v['name']);
	
    	}
    	$this->echoJson(array('result' => 0, 'hospital' => $result));
    } 
   //==========================================================================================
    //医院==>查询医生, 或者返回TOP 100的医生
	
//    public function getDoctor(){
//    	$hospitalid = intval(I('request.id', 0)); //hospital_id
//    	 
//    	$doctor_ds = D('Doctor');
//    	$hospitalid == 0 ? $doctor = $doctor_ds->order('renqi_cnt DESC')->limit(100)->select()
//    			 : $doctor = $doctor_ds->where('hospital_id='.$hospitalid)->select();
//    	 
//    	$result = array();
//    	foreach ($doctor as $k => $v){
//    		$result[] = array('id' => intval($v['id']), 'name' => $v['name']);
//    	}
//    	$this->echoJson(array('result' => 0, 'doctor' => $result));
//    }
	
	
	//入参 id 改为了解hospitalid ?
/*获取医生列表
三个条件参数，country，province ，hospitalid（int） 可以传入任意(0~3)个，以最小级别优先。
比如，http://121.40.78.46/tb/index.php?m=Home&c=App&a=getDoctor&country=中国&hospitalid=5, 则country=中国不起作用，以hospitalid=5为准。
比如，http://121.40.78.46/tb/index.php?m=Home&c=App&a=getDoctor&country=美国&province=上海, 则country=美国不起作用，以上海为准。
如果三个参数都不传，则取前面100个（以内部baiqiang_kpi排序）
//country: 以数字:  0为中国，1为美国. //如果为汉字，暂也可
*/
    public function getDoctor(){
    	$hospitalid = intval(I('request.hospitalid', 0)); //hospital_id    	
	$country = I('request.country');//国家	
		if($country == 0) {$country ='中国';}
		if($country == 1) {$country ='美国';}
		if($country == 2) {$country ='泰国';}
    	$province = I('request.province');//省	
//		if($province != '')
//		{
//		    $province_ds = D('province');
//			$proRec = $province_ds->where("provinceid=".$province)->find();
//			if($proRec != null)
//			{
//			    $province = $proRec[provincename];
//			}		
//        }	
  
		 
    	$hospital_ds = D('Hospital');
		/*
    	$hospital = $hospital_ds->where("country='".$country."' AND province='".$province."'")->select();
    	$hospitalids= array();
    	foreach ($hospital as $k => $v){
    		$result[] = array('id' => intval($v['id']),	'name' => $v['name']);
    	}*/

		
    	$doctor_ds = D('Doctor');
		
		//以最低那一级别的优先: 
		if($hospitalid > 0)
		{
		    $doctor = $doctor_ds->where('hospital_id='.$hospitalid." and auth_status=2")->select();
		}
		else if($province !="")
		{
			$hospital = $hospital_ds->where("zid='".$province."'")->select();
			$doctor = array();
			foreach ($hospital as $k => $v)
			{
				$ahosdoctor = $doctor_ds->where('hospital_id='.$v['id']." and auth_status=2")->select();
				foreach ($ahosdoctor as $k => $v){
                                        if($v['img']!=null){
                                            $v['img']='http://img.cndoc.ivf-bb.com/'.$v['img'];
                                        }
					$doctor[] = $v;
				}
			}					
		}
		else if($country !="")
		{
		    //$doctor = $doctor_ds->order('baiqiang_kpi DESC')->limit(100)->select();//临时这样???
			$hospital = $hospital_ds->where("country='".$country."'")->select();
			$doctor = array();
			foreach ($hospital as $k => $v)
			{
				$ahosdoctor = $doctor_ds->where('hospital_id='.$v['id']." and auth_status=2")->select();
				foreach ($ahosdoctor as $k => $v){
                                        if($v['img']!=null){
                                            $v['img']='http://img.cndoc.ivf-bb.com/'.$v['img'];
                                        }
					$doctor[] = $v;
				}
                                
			}				
		}
		else
		{
		    $doctor = $doctor_ds->where("auth_status=2")->order('baiqiang_kpi DESC')->limit(100)->select();
		}

    	 
    	$result = array();
    	foreach ($doctor as $k => $v){
                                        if($hospitalid > 0&&$v['img']!=null){
                                            $v['img']='http://img.cndoc.ivf-bb.com/'.$v['img'];
                                        }
                                        unset($v['logname']);
                                        unset($v['password']);
    		$result[] = $v;
			
    	}
    	$this->echoJson(array('result' => 0, 'doctor' => $result));
    }	
	
	//获取医生top N
	//type查找类型:1-人气，2-好评，3-专家百强
	//count: 最多返回多少记录
	//http://121.40.78.46/tb/index.php?m=Home&c=App&a=SearchDoctorTopN&type=1&count=50
 public function SearchDoctorTopN()
 {
 	$type = intval(I('request.type', 0)); //
	$count = intval(I('request.count', 0));
	if($count <= 0)
	{$count = 30;
	}
	
	$doctor_ds = D('Doctor');
	
	//以最低那一级别的优先: 
	if($type ==1) //不同用户点击次数
	{
		$doctor = $doctor_ds->where("auth_status=2")->order('renqi_cnt DESC')->limit($count)->select();
	}
	else if($type ==2) //关注人数
	{
		$doctor = $doctor_ds->where("auth_status=2")->order('haoping_cnt DESC')->limit($count)->select();//临时这样???
	}
	else if($type ==3) //未确定
	{
		$doctor = $doctor_ds->where("auth_status=2")->order('baiqiang_kpi DESC')->limit($count)->select();//临时这样???
	}
	else //自然
	{
		$doctor = $doctor_ds->where("auth_status=2")->order('renqi_cnt DESC')->limit($count)->select();
	}

	 
	$result = array();
	foreach ($doctor as $k => $v){
                    if($v['img']!=null){
                        $v['img']='http://img.cndoc.ivf-bb.com/'.$v['img'];
                    }
		$result[] = array('id' => intval($v['id']), 'name' => $v['name'],'img'=>$v['img']);
	}
	$this->echoJson(array('result' => 0, 'doctor' => $result));
} 
//======================================================================================================	
/*作废    
    //分页查询BBS消息, 下拉／上拉刷新／进入
    public function getTopic(){
    	$replytime = intval(I('request.ordertime'), 0)/1000;
    	$op = intval(I('request.op'), 0); //0-进入, 1-下拉取最新，2－上拉取历史
    	
    	$bbs_topic_ds = D('bbs_topic');
    	
    	switch ($op){
    		case 0:
    			$topic = $bbs_topic_ds->order('replytime DESC')->limit(20)->select();
    			break;
    		case 1:
    			$topic = $bbs_topic_ds->where('replytime > '.$replytime)->order('replytime DESC')->limit(20)->select();
    			break;
    		case 2:
    			$topic = $bbs_topic_ds->where('replytime < '.$replytime)->order('replytime DESC')->limit(20)->select();
    			break;
    	}
    	
    	$user_ds = D('User');
    	foreach ($topic as $k => $v){
    		$user = $user_ds->where('id='.$v['uid'])->find();
    		$topic[$k]['username'] = $user['name'];
    		$topic[$k]['id'] = intval($topic[$k]['id']);//???
    		$topic[$k]['post_time'] = $topic[$k]['post_time'] * 1000;//??
    		unset($topic[$k]['uid']);//注销定义的变量
    		unset($topic[$k]['replytime']);    		
    	}
    	
    	$this->echoJson(array('result' => 0, 'topic' => $topic));
    }
	*/
//-----------------------------------------------------------------------------------------------    
	//获取BBS主题列表（不包括帖子的详细内容）
	//type:int,bbs帖子类型,1:全部,2:最新（最新帖子的三天内帖子，秒计）,3:精华,4:置顶. 1/2是时间特性。3，4是属性。3和4可同时。
	//id:int,BBS主题的id号，方向: 从id起往小了数，不包括本id.  -1时取最新的(相当于id=无穷大)。
	//step:int,步长，即一次取多少条。	
	//http://121.40.78.46/tb/index.php?m=Home&c=App&a=getBBS&id=-1&step=10&type=1 
	//http://121.40.78.46/tb/index.php?m=Home&c=App&a=getBBS&id=5&step=3&type=1   	
public function getBBS(){
    	$type = intval(I('request.type'));
    	$id = intval(I('request.id'));
	$step = intval(I('request.step'));
    	$opt=intval(I('request.opt'));
    	$bbs_topic_ds = D('bbs_topic');
    	$doctor_id = I("request.doctor_id",'');
        $hospital_id = I("request.hospital_id",'');
        $where='';
        if($opt==4){
            $where=" and hospital_id=".$hospital_id;
            
        }elseif($opt==5){
            $where=" and doctor_id=".$doctor_id;
            
        }
        /*
    	switch ($op){
    		case 0:
    			$topic = $bbs_topic_ds->order('replytime DESC')->limit(20)->select();
    			break;
    		case 1:
    			$topic = $bbs_topic_ds->where('replytime > '.$replytime)->order('replytime DESC')->limit(20)->select();
    			break;
    		case 2:
    			$topic = $bbs_topic_ds->where('replytime < '.$replytime)->order('replytime DESC')->limit(20)->select();
    			break;
    	}*/
		
		//$this->echoJson(array('result' => 0, 'type' => $type));
		
		if($type == 3) //3:精华
		{
			if($id == -1) //第一次
			{
				$topic = $bbs_topic_ds->where('isjinghu=1 and visible=1 and opt='.$opt.$where)->order('id DESC')->limit($step)->select();
			}
			else //更多
			{
				$topic = $bbs_topic_ds->where('isjinghu=1 and visible=1 and id<' .$id.' and opt='.$opt.$where)->order('id DESC')->limit($step)->select();
			}		    
			
		}
		else if ($type == 4) //4:置顶.个数少，不需要“加载更多”
		{
		    $topic = $bbs_topic_ds->where('istop =1  and visible=1 and opt='.$opt.$where)->order('id DESC')->limit($step)->select();
		}
		else  if ($type == 1)//1全部
		{
			if($id == -1) //第一次
			{
				$topic = $bbs_topic_ds->where('istop=0 and isjinghu=0 and visible=1 and opt='.$opt.$where)->order('id DESC')->limit($step)->select();
			}
			else //更多
			{
				$topic = $bbs_topic_ds->where('istop=0 and isjinghu=0  and visible=1 and id<' .$id.' and opt='.$opt.$where)->order('id DESC')->limit($step)->select();
			}
		}
		else if ($type == 2)//2，先取最近三天。还需要日期条件。
		{
			$mostnewR = $bbs_topic_ds->where('opt='.$opt.$where)->order('post_time DESC')->limit(1)->find();//最新的帖子。
			$maxtime = $mostnewR['post_time'];//最近记录的时候。
			//$mintime = $maxtime - 259200;//3天=259200秒
			$mintime = $maxtime - 86400;//1天
			if($id == -1)
			{
				$topic = $bbs_topic_ds->where('istop=0 and isjinghu=0 and visible=1 and post_time>' . $mintime.' and opt='.$opt.$where)->order('id DESC')->limit($step)->select();
			}
			else
			{
				$topic = $bbs_topic_ds->where('istop=0 and isjinghu=0  and visible=1 and id<' .$id . ' and post_time>' . $mintime.' and opt='.$opt.$where )->order('id DESC')->limit($step)->select();
			}		
		}
		
		//$topic = $bbs_topic_ds->where('id < '.$id . ' and type=' .$type )->order('id DESC')->limit($step)->select();
    	
    	$user_ds = D('User');
		$doctor_ds = D('Doctor');
    	foreach ($topic as $k => $v){
    		if($v['postuserid']  < 100000000 )
			{
				$man = $user_ds->where('id='.$v['postuserid'])->find();
				$topic[$k]['postusername'] = $man['name'];
			}else
			{
				$man = $doctor_ds->where('id='.$v['postuserid'])->find();
				$topic[$k]['postusername'] = $man['logname'];				
			}		
    		
    		
    		$topic[$k]['id'] = intval($topic[$k]['id']);
    		$topic[$k]['post_time'] = $topic[$k]['post_time'] * 1000;
			$topic[$k]['avatar'] = $man['avatar'];

    		unset($topic[$k]['replytime']);  //只能全小写。  
            unset($topic[$k]['content']);//先不返回内容			
			unset($topic[$k]['visible']);
			unset($topic[$k]['istop']);
			unset($topic[$k]['isjinghu']);	
            unset($topic[$k]['attach']);			


    	}
    	
    	$this->echoJson(array('result' => 0, 'bbs' => $topic));
    }
//=========================================================================================	
/*根据BBS主题（不包括内容）查找帖子，最多返回50条。返回的结果同查询BBS帖子信息
http://121.40.78.46/tb/index.php?m=Home&c=App&a=searchBBS&type=1&filter=请问
type:int,bbs帖子类型,1:全部,2:最新（最新帖子的三天内帖子，秒计）,3:精华,4:置顶. 
filter:字符串，过滤关键字
*/
public function searchBBS(){
    	$type = intval(I('request.type'));
        $opt = I("request.opt");
        
        $doctor_id = I("request.doctor_id",'');
        $hospital_id = I("request.hospital_id",'');
    	//$id = intval(I('request.id'));
		$step = 50;//intval(I('request.step'));
		$filter = (I('request.filter'));
        $where='';
        if($opt==4){
            $where=" and hospital_id=".$hospital_id;
            
        }elseif($opt==5){
            $where=" and doctor_id=".$doctor_id;
            
        }
    	$bbs_topic_ds = D('bbs_topic');
		
		if($type == 3) //3:精华
		{
			$topic = $bbs_topic_ds->where('isjinghu=1 and visible=1 and opt='.$opt.$where.' (title like "%' .$filter . '%" or content like "%' . $filter . '%")')->order('id DESC')->limit($step)->select();
		}
		else if ($type == 4) //4:置顶.个数少，不需要“加载更多”
		{
		    $topic = $bbs_topic_ds->where('istop =1  and visible=1 and opt='.$opt.$where.' (title like "%' .$filter . '%" or content like "%' . $filter . '%")')->order('id DESC')->limit($step)->select();
		}
		else  if ($type == 1)//1全部
		{
			$topic = $bbs_topic_ds->where('istop=0 and isjinghu=0 and visible=1 and opt='.$opt.$where.' and (title like "%' .$filter . '%" or content like "%' . $filter . '%")')->order('id DESC')->limit($step)->select();
		}
		else if ($type == 2)//2，先取最近三天。还需要日期条件。
		{
			$mostnewR = $bbs_topic_ds->where('opt='.$opt.$where)->order('post_time DESC')->limit(1)->find();//最新的帖子。
			$maxtime = $mostnewR['post_time'];//最近记录的时候。
			//$mintime = $maxtime - 259200;//3天=259200秒
			$mintime = $maxtime - 86400;//1天

			$topic = $bbs_topic_ds->where('istop=0 and isjinghu=0  and visible=1 and opt='.$opt.$where.' and (title like "%' .$filter . '%" or content like "%' . $filter . '%") and post_time>' . $mintime )->order('id DESC')->limit($step)->select();
	
		}
		
   	
    	$user_ds = D('User');
    	foreach ($topic as $k => $v){
    		$user = $user_ds->where('id='.$v['postuserid'])->find();
    		$topic[$k]['postusername'] = $user['name'];
    		$topic[$k]['id'] = intval($topic[$k]['id']);
    		$topic[$k]['post_time'] = $topic[$k]['post_time'] * 1000;
			$topic[$k]['avatar'] = $user['avatar'];

    		unset($topic[$k]['replytime']);  //只能全小写。  
            unset($topic[$k]['content']);//先不返回内容			
			unset($topic[$k]['visible']);
			unset($topic[$k]['istop']);
			unset($topic[$k]['isjinghu']);			
    	}
    	
    	$this->echoJson(array('result' => 0, 'bbs' => $topic));
    }



	//--------------------------------------------------------------------------------------
	//用户在点击一条帖子的主题后，展开其具体内容(不包含别人回复)，返回结果中带有图片的url（如果有的话）
//http://121.40.78.46/tb/index.php?m=Home&c=App&a=getABbsContent&id=5
//id: int,帖子的id
public function getABbsContent(){
    	$id = intval(I('request.id'));
    	
    	$bbs_topic_ds = D('bbs_topic');
		
        $bbs_topic_ds->startTrans();
        $res = $bbs_topic_ds->where('id='.$id)->setInc('viewcount', 1);
       	$bbs_topic_ds->commit();
		
		$BbsCont = $bbs_topic_ds->where('visible=1 and id=' .$id)->select();
    	$user_ds = D('User');
		$doctor_ds = D('Doctor');
    	foreach ($BbsCont as $k => $v)
		{
    		if($v['postuserid']  < 100000000 )
			{
				$man = $user_ds->where('id='.$v['postuserid'])->find();
				$BbsCont[$k]['postusername'] = $man['name'];
                                if($man['image']!=null){
                                    $BbsCont[$k]['postuserimg']="http://img.user.ivf-bb.com/" . rtrim($man['image'], ',');
                                }else{
                                    $BbsCont[$k]['postuserimg']='';
                                }
                                
			}else
			{
				$man = $doctor_ds->where('id='.$v['postuserid'])->find();
				$BbsCont[$k]['postusername'] = $man['logname'];
                                if($man['img']!=null){
                                    $BbsCont[$k]['postuserimg']='http://img.cndoc.ivf-bb.com/' . $man['img'];
                                }else{
                                    $BbsCont[$k]['postuserimg']='';
                                }
			}		
    		
    		
    		$BbsCont[$k]['id'] = intval($BbsCont[$k]['id']);
    		$BbsCont[$k]['post_time'] = $BbsCont[$k]['post_time'] * 1000;
			$BbsCont[$k]['avatar'] = $man['avatar'];
    		unset($BbsCont[$k]['replytime']);  //只能全小写。  
            //unset($BbsCont[$k]['content']);//与上一函数相比，就多这个。			
			unset($BbsCont[$k]['visible']);
			unset($BbsCont[$k]['istop']);
			unset($BbsCont[$k]['isjinghu']);	

            $attachx = explode(",",$BbsCont[$k]['attach']);
			if( count($attachx) > 0) //不能用$attachx != null
			{
				$attachOut = array();
				foreach ($attachx as $aattach){
				    if($aattach != null  && $aattach !='')
					{
					    $attachOut[] = 'http://bbsimg.ivf-bb.com/' . $aattach;
					}
				}	
				$BbsCont[$k]['attach'] = $attachOut;	
			}
			//else
			{
			   // $BbsCont[$k]['attach'] = "";
			}
			
			
    	}    	
		
    	$this->echoJson(array('result' => 0, 'BbsCont' => $BbsCont));
    }	
//======================================================================================================	
/*作废    
    //用户发表TOPIC
	//http://121.40.78.46/tb/index.php?m=Home&c=App&a=addBBS&topic="title1"&content="ccc"
    public function newTopic(){
    	$uid = 1;// $this->checkUserTag();
    	
    	$topic = I('request.topic');
    	$content = I('request.content');
    	
    	$data['postuserid'] = $uid;
		$data['title'] = $topic;
		$data['post_time'] = time();
    	$data['content'] = $content;
    	
    	
    	
    	$bbs_topic_ds = D('bbs_topic');
    	$topic_id = $bbs_topic_ds->add($data);
    	if (!$topic_id)
    		$this->echoJson(array('result' => 1, 'reason' => '话题保存失败'));
    	else
    		$this->echoJson(array('result' => 0, 'topic_id' => $topic_id));
    }
	*/
//--------------------------------------------------------------------------------------------------------
    //用户发表一个帖子
	//http://121.40.78.46/tb/index.php?m=Home&c=App&a=addBBS&title=标题&content=内容&uid=1
	//uid:  int,用户id（发表者）
	//title:字符串，标题
	//content: 字符串，内容
    public function addBBS(){
	    $uid = intval(I('request.uid'));//如果不带此参，获取值为0
            $lat = I('request.lat');
            $lng = I('request.lng');
            $opt = I("request.opt");
            $doctor_id = I("request.doctor_id",'');
            $hospital_id = I("request.hospital_id",'');
    	$title = I('request.title');
    	$content = I('request.content');		
		
		//------------------------------------------
    	
    	$data['postuserid'] = $uid;
		$data['title'] = $title;
    	$data['post_time'] = time();
		$data['replytime'] = time();
        $data['reply_num'] = '0';				
		$data['viewcount'] = '0';
    	$data['content'] = $content;
		$data['isopen'] = '1';  
        $data['lat']=$lat;
        $data['lng']=$lng;
	$data['opt']=$opt;
        $data['doctor_id']=$doctor_id;
        $data['hospital_id']=$hospital_id;
        //global $uploadfiles;
/*		
$myfilex = fopen("qqqq3.txt", "w") or die("Unable to open file!");	
fwrite($myfilex, "\nuploadfiles=" .$uploadfiles['xxxx']);
fwrite($myfilex, "\ntime=" . time());
fclose($myfilex);	*/	


        $temp_info = D('temp_info'); 
		$atta =  $temp_info->where('uid='. $uid)->find(); 
		if($atta == null)
		{
		    $data['attach']  ='';
		}
		else
		{
		    $data['attach'] = $atta['attach'];//$uploadfiles['xxxx'];//$uid . '-1.jpg';
			$temp_info->where('uid='. $uid)->delete(); 
		}
		
		
		
		//$data['attach'] = $uid . '-1.jpg';
		//unset($uploadfiles[$uid]);  		
    	
    	$bbs_topic_ds = D('bbs_topic');
    	$topic_id = $bbs_topic_ds->add($data);//返回那个自增的id
    	if (!$topic_id)
    		$this->echoJson(array('result' => 1, 'reason' => '话题保存失败'));
    	else
    		$this->echoJson(array('result' => 0, 'topic_id' => $topic_id));
    }    
	//==============================================================
    //用户发表回复
	/*
    public function newReply(){
    	$uid = $this->checkUserTag();
    	
    	$topic_id = intval(I('topicid'));
        $reply = I('reply');//回贴子本身replyid=-1，回复的回复时<>-1
        
        $data['uid'] = $uid;
        $data['reply'] = $reply;
        $data['reply_time'] = time();
        $data['topic_id'] = $topic_id;
        $data['parent_id'] = $topic_id;
        $bbs_topic_ds = D('bbs_topic');
        $bbs_topic_reply_ds = D('bbs_topic_reply');
        
        $bbs_topic_ds->startTrans();
        $reply_id = $bbs_topic_reply_ds->add($data);
        $result1 = $bbs_topic_ds->where('id='.$topic_id)->setField('replytime', time());
        $result2 = $bbs_topic_ds->where('id='.$topic_id)->setInc('reply_num', 1);
        if ($reply_id and $result1 and $result2) {
        	$bbs_topic_ds->commit();
        	$this->echoJson(array('result' => 0, 'reply_id' => $reply_id));
        } else {
        	$bbs_topic_ds->rollback();
        	$this->echoJson(array('result' => 1, 'reason' => '回复数据保存失败'));
        }
    } */
	//用户针对一个帖子发表回复。
	//http://121.40.78.46/tb/index.php?m=Home&c=App&a=newReply&uid=1&topicid=6&parentid=-1&content=回复内容
	//topicid:int, 主题帖子的id
	//parentid: int, -1针对主题帖子的回复。!=-1时，是此主题下，针对回复的回复，此parentid即为前一个回复的id。
	//content: 字符串，回复的内容。
   public function newReply(){
		
    	$topic_id = intval(I('request.topicid'));
		$parentid = intval(I('request.parentid'));//被回复的id,回贴子本身replyid=-1，

	    $uid = intval(I('request.uid'));//如果不带此参，获取值为0
	
		if( $uid ==0) //is_null($userid)无效 
		{
			$uid = 1;//或者返回失败???
		}  		
        $content = I('request.content');      


        $data['topic_id'] = $topic_id;
        $data['parent_id'] = $parentid;
        $data['uid'] = $uid;
        $data['reply'] = $content;
		$data['reply_time'] = time();
		//$data['reply_num']  //未使用 reply_num 字段
		
		
		$temp_info = D('temp_info'); 
		$atta =  $temp_info->where('uid='. $uid)->find(); 
		if(($atta == null))
		{
		    $data['attach'] = "";
		}
		else
		{
		   $data['attach'] = $atta['attach'];//$uploadfiles['xxxx'];//$uid . '-1.jpg';
		   $temp_info->where('uid='. $uid)->delete(); 
		}
		 		
        $bbs_topic_ds = D('bbs_topic');
        $bbs_topic_reply_ds = D('bbs_topic_reply');//BbsTopicReply
      
        $bbs_topic_ds->startTrans();
		
        $reply_id = $bbs_topic_reply_ds->add($data);
  		
        $r1 = $bbs_topic_ds->where('id='.$topic_id)->setField('replytime', time());
        $r2 = $bbs_topic_ds->where('id='.$topic_id)->setInc('reply_num', 1);
		
        if ($reply_id and $r1 and $r2) {
        	$bbs_topic_ds->commit();
        	$this->echoJson(array('result' => 0, 'reply_id' => $reply_id));
        } else {
        	$bbs_topic_ds->rollback();
        	$this->echoJson(array('result' => 1, 'reason' => '回复数据保存失败'));
        }
    }	
//====================================================================================    
    //用户点击TOPIC，查看所有回复
	/*
    public function getReply(){
    	$uid = $this->checkUserTag();
    	 
    	$topic_id = intval(I('topicid'));
    	$reply_time = intval(I('replytime'), 0)/1000;
    	$op = intval(I('op')); //0-进入, 1-下拉取最新, 2-上拉取历史
    	
    	$bbs_topic_reply_ds = D('bbs_topic_reply');    	
    	switch ($op){
    		case 0:
    			$reply = $bbs_topic_reply_ds->where('topic_id='.$topic_id)
    										->order('reply_time DESC')->limit(20)->select();
    			break;
    		case 1:
    			$reply = $bbs_topic_reply_ds->where('topic_id='.$topic_id.' AND reply_time > '.$reply_time)
    										->order('reply_time DESC')->limit(20)->select();
    			break;
    		case 2:
    			$reply = $bbs_topic_reply_ds->where('topic_id='.$topic_id.' AND reply_time < '.$reply_time)
    										->order('$reply_time DESC')->limit(20)->select();
    			break;
    	}
    	
    	$user_ds = D('User');
    	foreach ($reply as $k => $v){
    		$user = $user_ds->where('id='.$v['uid'])->find();
    		$reply[$k]['username'] = $user['name'];
    		$reply[$k]['id'] = intval($reply[$k]['id']);
    		$reply[$k]['reply_time'] = $reply[$k]['reply_time'] * 1000;
    		unset($reply[$k]['uid']);    		
    	}
    	 
    	$this->echoJson(array('result' => 0, 'reply' => $reply));    	
    }*/
	
	//获取一个主题帖子的所有回复帖子。
	//http://121.40.78.46/tb/index.php?m=Home&c=App&a=getReply&topicid=6&replyid=-1&step=10
	//topicid:int, 主题帖子的id
	//replyid:int, 当=-1时即取最新的，否则(加载更多内容或翻页时)从这个回复id起往下取更多的老帖子。
	//step:int, 返回多少条记录。
	//返回结果中，parent_id:如果=-1则是直接针对主题的回复。否则，则是针对回复的回复.
	//bug:回复的回复内容是不对的。http://121.40.78.46/tb/index.php?m=Home&c=App&a=getReply&topicid=418&replyid=-1&step=10
   public function getReply(){  	 
    	$topic_id = intval(I('request.topicid'));

		$preid=intval(I('request.replyid'));
		$step=intval(I('request.step'));
		
    	//$op = intval(I('request.op')); //0-进入, 1-下拉取最新, 2-上拉取历史
    	
    	$bbs_topic_reply_ds = D('bbs_topic_reply');    	
    	if($preid == -1){
    			$reply = $bbs_topic_reply_ds->where('topic_id='.$topic_id)
    										->order('id')->limit($step)->select();
    	}
		else { ////1-下拉取最新,
    			$reply = $bbs_topic_reply_ds->where('topic_id='.$topic_id.' AND id > '.$preid)
    										->order('id ')->limit($step)->select();
    	}
    	
    	$user_ds = D('User');
		$doctor_ds = D('Doctor');
    	foreach ($reply as $k => $v){
		
    		if($v['uid']  < 100000000 )
			{
				$man = $user_ds->where('id='.$v['uid'])->find();
				$reply[$k]['username'] = $man['name'];
                                if($man['image'] != null)
					{				
					    $reply[$k]['image']  = "http://img.user.ivf-bb.com/" . rtrim($man['image'],",");
                                        }else{
                                            $reply[$k]['image'] ='';
                                        }
			}else
			{
				$man = $doctor_ds->where('id='.$v['uid'])->find();
				$reply[$k]['username'] = $man['logname'];
                                if($man['img'] != null)
					{				
					    $reply[$k]['image']  ='http://img.cndoc.ivf-bb.com/' .$man['img'];
                                        }else{
                                            $reply[$k]['image'] ='';
                                        }
			}
			
    		$reply[$k]['id'] = intval($reply[$k]['id']);//??干啥?
    		$reply[$k]['reply_time'] = $reply[$k]['reply_time']*1000;
			$reply[$k]['content'] = $reply[$k]['reply'];
			
    		//被回复信息: 
			if($v['parent_id']==0 || $v['parent_id']==-1)
			{
				$reply[$k]['parent_id'] =-1;
			}
			else
			{
				$bereply = $bbs_topic_reply_ds->where('id='.$v['parent_id'])->find();
				
				$reply[$k]['parentuid'] = $bereply['uid'];//，被回复人id
				
				if($v['uid']  < 100000000 )
				{
					$man = $user_ds->where('id='. $bereply['uid'])->find();
					$reply[$k]['parentusername'] = $man['name'];//被回复人名称	
                                        if($man['image'] != null)
					{				
					    $reply[$k]['imageto']  = "http://img.user.ivf-bb.com/" . rtrim($man['image'],",");
                                        }else{
                                            $reply[$k]['imageto'] ='';
                                        }
				}else
				{
					$man = $doctor_ds->where('id='. $bereply['uid'])->find();
					$reply[$k]['parentusername'] = $man['logname'];//被回复人名称
                                        if($man['img'] != null)
					{				
					    $reply[$k]['imageto']  = 'http://img.cndoc.ivf-bb.com/' .$man['img'];
                                        }else{
                                            $reply[$k]['imageto'] ='';
                                        }
				}				

					
				$reply[$k]['parentcontent'] = $bereply['reply'] ;//被回复内容
				$reply[$k]['parentpostdate'] = $bereply['reply_time']*1000;	//被回复内容时间		
			}
			
    		unset($reply[$k]['reply']); 
			unset($reply[$k]['reply_num']);		

            $attachx = explode(",",$reply[$k]['attach']);
			if( count($attachx) > 0)
			{			
				$attachOut = array();
				foreach ($attachx as $aattach){   
				    if($aattach != null  && $aattach !='')
					{				
					    $attachOut[] = 'http://bbsimg.ivf-bb.com/' . $aattach;
					}
				}	
				$reply[$k]['attach'] = $attachOut;		
            }	
			else
			{
				//$reply[$k]['attach'] = $attachOut;
			}			
    	} //for
    	 
    	$this->echoJson(array('result' => 0, 'reply' => $reply));    	
    }	
//====================================================================================	
	/*
	搜索楼主对自己的回复（只看楼主功能）
	http://121.40.78.46/tb/index.php?m=Home&c=App&a=searchReply&topicid=6&userid=1
	topicid:int, 帖子id
	userid:int, 楼主id
*/	
 public function searchReply(){
    	    	 
    	$topic_id = intval(I('request.topicid'));
		$uid = intval(I('request.userid'));
		
$myfilex = fopen("qq-searchReply.txt", "w") or die("Unable to open file!");
fwrite($myfilex, "\ntopic_id=" .$topic_id);
fwrite($myfilex, "\nuid=" .$uid);
fclose($myfilex);		
		//$preid=intval(I('request.replyid'));
		$step= 50;//intval(I('request.step'));
		
    	//$op = intval(I('request.op')); //0-进入, 1-下拉取最新, 2-上拉取历史
    	
    	$bbs_topic_reply_ds = D('bbs_topic_reply');    	

    	$reply = $bbs_topic_reply_ds->where('topic_id='.$topic_id .' and uid=' .$uid )
    								->order('id')->limit($step)->select();

    	
    	$user_ds = D('User');
    	foreach ($reply as $k => $v)
		{
    		$user = $user_ds->where('id='.$v['uid'])->find();
    		$reply[$k]['username'] = $user['name'];
    		$reply[$k]['id'] = intval($reply[$k]['id']);//??干啥?
    		$reply[$k]['reply_time'] = $reply[$k]['reply_time']*1000;
			$reply[$k]['content'] = $reply[$k]['reply'];
			
    		//被回复信息: 
			if($v['parent_id']==0 || $v['parent_id']==-1)
			{
				$reply[$k]['parent_id'] =-1;
			}
			else
			{
				$bereply = $bbs_topic_reply_ds->where('parent_id='.$v['parent_id'])->find();
				
				$reply[$k]['parentuid'] = $bereply['uid'];//，被回复人id
				$user = $user_ds->where('id='. $bereply['uid'])->find();
				$reply[$k]['parentusername'] = $user['name'];//被回复人名称
				$reply[$k]['parentcontent'] = $bereply['reply'] ;//被回复内容
				$reply[$k]['parentpostdate'] = $bereply['reply_time']*1000;	//被回复内容时间		
			}
			
    		unset($reply[$k]['reply']); 
			unset($reply[$k]['reply_num']);	

			$attachx = explode(",",$reply[$k]['attach']);
			if( count($attachx) > 0)
			{			
				$attachOut = array();
				foreach ($attachx as $aattach){   
				    if($aattach != null  && $aattach !='')
					{				
					    $attachOut[] = 'http://bbsimg.ivf-bb.com/' . $aattach;
					}
				}	
				$reply[$k]['attach'] = $attachOut;		
            }	
    	}
  //fwrite($myfilex, "\nooooo");  
  //fclose($myfilex);
    	$this->echoJson(array('result' => 0, 'reply' => $reply));    	
    }	
 

//======================================================================================================
    //获取聊天内容,http://121.40.78.46/tb/index.php?m=Home&c=App&a=getMessage&fromuserid=1&touserid=2&direction=1&id=0&step=10
	//用户1（我）与用户2的聊天内容
	//direction:方向，0-进入, 1-下拉取最新, 2-上拉取历史
	/*
    public function getMessage(){
    	$fromuserid = intval(I('request.fromuserid'));//我
    	$touserid = intval(I('request.touserid'));
		
		$drct = intval(I('request.direction')); //无参数即为0-进入, 1-下拉取最新, 2-上拉取历史

		
		$preid =  intval(I('request.id'));//前一个id
		$step =  intval(I('request.step'));
		
		if($fromuserid < $touserid)
		{
		  $littleuid =$fromuserid;
		  $biguid =$touserid;
		}
		else
		{
		  $littleuid =$touserid;
		  $biguid =$fromuserid;		
		}
    	
    	$chat_ds = D('chat');		

    	switch ($drct){
    		case 0:
					//$mostnewR = $chat_ds->where('littleuid='.$littleuid . ' and biguid=' .$biguid)
					//        ->order('id DESC')->limit(1)->find();//最新的记录。
					//$preid = $mostnewR['id'];//最近记录的时候。

    			$chat = $chat_ds->where('littleuid='.$littleuid . ' and biguid=' .$biguid)
    										->order('id DESC')->limit($step)->select();
    			break;
    		case 1: //最新
    			$chat = $chat_ds->where('littleuid='.$littleuid . ' and biguid=' .$biguid.' AND id > '.$preid)
    										->order('id DESC')->limit($step)->select();
    			break;
    		case 2://历史
    			$chat = $chat_ds->where('littleuid='.$littleuid . ' and biguid=' .$biguid.' AND id < '.$preid)
    										->order('$id DESC')->limit($step)->select();
    			break;
    	}
    	
    	$user_ds = D('User');
    	foreach ($chat as $k => $v){
    		$user = $user_ds->where('id='.$v['speakuid'])->find();
			if($v['speakuid'] == $fromuserid)
			{
				$chat[$k]['fromuserid'] = $fromuserid;
				$chat[$k]['fromusername'] = $user['name'];
			}
			else
			{
				$chat[$k]['touserid'] = $fromuserid;
				$chat[$k]['tousername'] = $user['name'];			
			}
			
			$chat[$k]['speaktime'] = $chat[$k]['speaktime'] * 1000;
    		unset($chat[$k]['littleuid']);    		
			unset($chat[$k]['biguid']); 
			unset($chat[$k]['speakuid']); 

    	}
    	//剩下:message,speaktime 
    	$this->echoJson(array('result' => 0, 'chat' => $chat));   
    }
	*/
	
	//增加考虑群聊的情形。
    //获取聊天内容,包括单聊和群聊。
	//http://121.40.78.46/tb/index.php?m=Home&c=App&a=getMessage&groupid=-1&fromuserid=11&touserid=2&direction=1&id=0&step=10 //单聊
	//http://121.40.78.46/tb/index.php?m=Home&c=App&a=getMessage&groupid=21&fromuserid=未用&touserid=未用&direction=1&id=0&step=10 //群聊
	//groupid:聊天群组的id,-1或0为单聊，否则(>0)为群聊。
	//fromuserid:int,说话的人。群聊时无用可不传。
	//touserid: int,说话的对象。群聊时无用可不传。
	//direction:int,方向，0-刚进入取最新的, 1-下拉取更新记录, 2-上拉取历史记录	
	//id:int,一个聊天信息的id，从它开始取后面的记录，不包括它自己。
	//step: int,取多少条聊天信息。
   public function getMessage(){
    	$groupid = intval(I('request.groupid'));
		$fromuserid = intval(I('request.fromuserid'));//我
                $touserid = intval(I('request.touserid'));
		
		$drct = intval(I('request.direction')); //无参数即为0-进入, 1-下拉取最新, 2-上拉取历史
		
		$preid =  intval(I('request.id'));//前一个id
		$step =  intval(I('request.step'));
		
		$chat_ds = D('chat');
		$user_ds = D('User');
		$doctor_ds = D('Doctor');
		
		if($groupid == -1 || $groupid==0) //单聊
		{
			if($fromuserid < $touserid)
			{
			  $littleuid =$fromuserid;
			  $biguid =$touserid;
			}
			else
			{
			  $littleuid =$touserid;
			  $biguid =$fromuserid;		
			}					

			switch ($drct){
				case 0:
					$chat = $chat_ds->where('littleuid='.$littleuid . ' and biguid=' .$biguid)
												->order('id DESC')->limit($step)->select();
					break;
				case 1: //最新
					$chat = $chat_ds->where('littleuid='.$littleuid . ' and biguid=' .$biguid.' AND id > '.$preid)
												->order('id DESC')->limit($step)->select();
					break;
				case 2://历史
					$chat = $chat_ds->where('littleuid='.$littleuid . ' and biguid=' .$biguid.' AND id < '.$preid)
												->order('$id DESC')->limit($step)->select();
					break;
			}
		
		}
		else //群聊
		{
			switch ($drct){
				case 0:
					$chat = $chat_ds->where('groupid='.$groupid )
												->order('id DESC')->limit($step)->select();
					break;
				case 1: //最新
					$chat = $chat_ds->where('groupid='.$groupid .' AND id > '.$preid)
												->order('id DESC')->limit($step)->select();
					break;
				case 2://历史
					$chat = $chat_ds->where('groupid='.$groupid .' AND id < '.$preid)
												->order('$id DESC')->limit($step)->select();
					break;
			}		
		}
    	
    	
    	foreach ($chat as $k => $v){
    		//$speaker = $user_ds->where('id='.$v['speakuid'])->find();
			if($v['speakuid'] > 100000000)
			{
				$speaker = $doctor_ds->where('id='.$v['speakuid'])->find();
                                if($speaker['img']!=null){
                                    $speaker['image']='http://img.cndoc.ivf-bb.com/'.$speaker['img'];
                                }else{
                                    $speaker['image']='';
                                }
			}else{
				$speaker = $user_ds->where('id='.$v['speakuid'])->find();
                                if($speaker['image']!=null){
                                    $speaker['image']="http://img.user.ivf-bb.com/".rtrim($speaker['image'],',');
                                }else{
                                    $speaker['image']='';
                                }
			}	
			
			if($v['speakuid'] == $fromuserid)
			{
				$chat[$k]['fromuserid'] = $fromuserid;
				$chat[$k]['fromusername'] = $speaker['name'];
                                $chat[$k]['image'] = $speaker['image'];
			}
			else
			{
				$chat[$k]['touserid'] = $fromuserid;
				$chat[$k]['tousername'] = $speaker['name'];
                                $chat[$k]['image'] = $speaker['image'];
			}
			
			$chat[$k]['speaktime'] = $chat[$k]['speaktime'] * 1000;
    		unset($chat[$k]['littleuid']);    		
			unset($chat[$k]['biguid']); 
			//unset($chat[$k]['speakuid']); 

    	}
    	//剩下:message,speaktime 
    	$this->echoJson(array('result' => 0, 'chat' => $chat));   
    }	
	//=======================================================================================
//http://121.40.78.46/tb/index.php?m=Home&c=App&a=sendMessage&fromuserid=1&touserid=2&message=hello	
/*
 public function sendMessage()
 {
 
		$myfilex = fopen("qqqq1.txt", "w") or die("Unable to open file!");
		fwrite($myfilex, "sendMessage");
		fclose($myfilex);


		$fromuserid = intval(I('request.fromuserid'));//我
		$touserid = intval(I('request.touserid'));

		$message = I('request.message');

		if($fromuserid < $touserid)
		{
			$littleuid =$fromuserid;
			$biguid =$touserid;
		}
		else
		{
			$littleuid =$touserid;
			$biguid =$fromuserid;		
		}	
	
	
    	$data['littleuid'] = $littleuid;
    	$data['biguid'] = $biguid;
		$data['speakuid'] = $fromuserid;
		$data['message'] = $message; 
    	$data['speaktime'] = time();
		
    	
    	$chat_ds = D('chat');   	
  
    	$msgid = $chat_ds->add($data);	
		return 0;
 }
 */
 
 //改造成可以群聊的情形
 //聊天发送一条信息: 
//http://121.40.78.46/tb/index.php?m=Home&c=App&a=sendMessage&groupid=-1&fromuserid=1&touserid=2&message=你好
//http://121.40.78.46/tb/index.php?m=Home&c=App&a=sendMessage&groupid=8&fromuserid=1&touserid=未用&message=大家好
//http://121.40.78.46/tb/index.php?m=Home&c=App&a=sendMessage&groupid=-1&fromuserid=1&touserid=2&message=[pic]  //发图片时，先 a=uploadfile&type=4，然后发本条。
//http://121.40.78.46/tb/index.php?m=Home&c=App&a=sendMessage&groupid=-1&fromuserid=1&touserid=2&message=[aud]&timelen=13s  //发声音时，先 a=uploadfile&type=5，然后发本条。
	//groupid:int, 聊天群组的id,-1或0为单聊，否则(>0)为群聊。
	//fromuserid:int, 说话的人。
	//touserid: int, 说话的对象。群聊时无用可不传。
	//message:字符串，聊天信息。
	//timelen ：语音的时长，一个字符串。
 public function sendMessage()
 {
        $groupid    = intval(I('request.groupid'));
		$fromuserid = intval(I('request.fromuserid'));//我
		$touserid   = intval(I('request.touserid'));
		$message    = I('request.message');
		$timelen    = I('request.timelen');
		
		$user_ds = D('User');
	    $doctor_ds = D('Doctor');
	    $chatlist_ds = D('chatlist'); 
		$chat_ds = D('chat');
		$heartbeatmsg_ds = D('heartbeat_msgtable');
		$groupchatid_ds = D('groupchat_id'); 
/*
$myfilex = fopen("qq-sendMessage.txt", "w") or die("Unable to open file!");
fwrite($myfilex, "\ngroupid=" .$groupid);
fwrite($myfilex, "\nfromuserid=" .$fromuserid);
fwrite($myfilex, "\ntouserid=" .$touserid);
fwrite($myfilex, "\nmessage=" .$message);
fclose($myfilex);
*/
		
		
		
		if($message == '[pic]' || $message == '[aud]') //图片消息,音频消息
		{
			$temp_info = D('temp_info'); 
			$atta = $temp_info->where('uid='. $fromuserid)->find(); 
			if($message == '[pic]')
			{
			    $message = $message . $atta['attach'];//获取消息，如:  [pic]6-1456391044-1.jpg
			}
			else
			{
			    $message = $message . $atta['attach'] . $timelen; //[aud]6-1456391044-1.amr,13s  注意 $atta['attach']  本身带有逗号。
			}			
			$temp_info->where('uid='. $fromuserid)->delete(); 		
		}

		
		if($groupid == -1) //单聊
		{
			if($fromuserid < $touserid)
			{
				$littleuid =$fromuserid;
				$biguid =$touserid;
			}
			else
			{
				$littleuid =$touserid;
				$biguid =$fromuserid;		
			}
		}
		else //群聊
		{
			$littleuid = -1;//$fromuserid;//有用
			$biguid = -1;//$groupid;//有用
		}
	
	
	
    	$data['groupid'] = $groupid;
		$data['littleuid'] = $littleuid;
    	$data['biguid'] = $biguid;
		$data['speakuid'] = $fromuserid;
		$data['message'] = $message; 
    	$data['speaktime'] = time();
  	
    	   	
  
    	$msgid = $chat_ds->add($data);	
		
		//注册消息。
		/*
			
		$data2['uid'] = $touserid;
		$data2['msgid'] ='5';
		$data2['todo'] ='searchChatObj';		
		$data2['time'] =time();			
		$data2['timex'] =date("Ymd H:i:s",$data2['time']); //可读形式	
		
		$heartbeatmsg_ds->add($data2);*/
		
		//修改消息列表，注册心跳消息
		if($groupid == -1) //单聊
		{
            $rec = $chatlist_ds->where('myuid='.$fromuserid . ' and uid=' .$touserid)->select();
			if($rec == null)
			{
                $chatlistr['myuid']	=$fromuserid;
				$chatlistr['groupid']	=-1;
				$chatlistr['uid']	= $touserid;
				if($touserid > 100000000)
				{
					$CtObj   = $doctor_ds->where('id='.$touserid)->find();					
				}
				else
				{
					$CtObj   = $user_ds->where('id='.$touserid)->find();						
				}
				$chatlistr['objName']	= $CtObj['name'];
				    						
				$chatlistr['speaktime']	=time();
				$chatlist_ds->add($chatlistr);	

                //反向再添加一次。
				$chatlistr['myuid']	=$touserid;
				$chatlistr['uid']	= $fromuserid;
				if($fromuserid > 100000000)
				{
					$CtObj   = $doctor_ds->where('id='.$fromuserid)->find();					
				}
				else
				{
					$CtObj   = $user_ds->where('id='.$fromuserid)->find();						
				}
				$chatlistr['objName']	= $CtObj['name'];				
				
                $chatlist_ds->add($chatlistr);					
				
			}
			else
			{
			    $chatlist_ds->where('myuid='.$fromuserid . ' and uid=' .$touserid)->setField('speaktime', time());
                $chatlist_ds->where('myuid='.$touserid . ' and uid=' .$fromuserid)->setField('speaktime', time());				
			}
			
			$data2['uid'] = $touserid;
			$data2['msgid'] ='5';
			$data2['todo'] ='searchChatObj';//当APP收到这个消息时，如果当前在消息列表界面，则 searchChatObj 刷新，
			    //如果在聊天界面，则(注意!!)不调用searchChatObj，但调用 getMessage		
			    //如果不在上述两个界面，则什么都不做(不要调用searchChatObj !!)。
			$data2['time'] =time();			
			$data2['timex'] =date("Ymd H:i:s",$data2['time']); 				
			$heartbeatmsg_ds->add($data2);		
		}
		else //群聊
		{
            $rec = $groupchatid_ds->where('groupchat_id='.$groupid)->find();
			if( $rec !=null)
			{
			    $uidarr = explode(";",$rec['userdoctor_ids']);
				foreach ($uidarr as $auid)
				{
				    if($auid != null  && $auid !='')
					{
					    //$rec = $chatlist_ds->where('myuid='.$auid . ' and groupid=' .$groupid)->find();//一定有
						$speaktime = time();
						$chatlist_ds->where('myuid='.$auid . ' and groupid=' .$groupid)->setField('speaktime', $speaktime);
						
						$data2['uid'] = $auid;//被提醒的人
						$data2['msgid'] ='5';
						$data2['todo'] ='searchChatObj';//当APP收到这个消息时，如果当前在消息列表界面，则 searchChatObj 刷新，
							//如果在聊天界面，则(注意!!)不调用searchChatObj，但调用 getMessage		
							//如果不在上述两个界面，则什么都不做(不要调用searchChatObj !!)。
						$data2['time'] =time();			
						$data2['timex'] =date("Ymd H:i:s",$data2['time']); 				
						$heartbeatmsg_ds->add($data2);							
					}
				}				 
			}
			
		}		
                if($groupid == -1||$groupid == 0){
                    if($touserid>100000000){
                        $this->Jpush("你有新消息,点击查看",array('tag'=>array("$touserid")),"doctor",$fromuserid); 
                    }else{
                        $this->Jpush("你有新消息,点击查看",array('tag'=>array("$touserid")),"",$fromuserid); 
                    }
                } 
		//return 0;
		$this->echoJson(array('result' => 0, 'sendMessage' => 'OK')); 
 }
//====================================================================================================== 

 //======================================================================================================
//http://121.40.78.46/tb/index.php?m=Home&c=App&a=searchChatObj&uid=9	
//查找聊天对象，放在 我的咨询 列表中。就象微信的默认界面中那个。
/*
 public function searchChatObj()
{
    $uid = intval(I('request.uid'));
	$chat_ds = D('chat');   
	$user_ds = D('User');
	$doctor_ds = D('Doctor');
	$step = 50;
	
	$chatObj =array();
	
	$talkto1 = $chat_ds->where('biguid=' .$uid)->Distinct(true)->field('littleuid')
								->order('speaktime desc')->limit($step)->select();
								
								
    	
	foreach ($talkto1 as $k => $v)
	{
		$CtObj = $user_ds->where('id='.$v['littleuid'])->find();
		$chatObj[$k]['uid'] = $v['littleuid'];
		$chatObj[$k]['objName'] = $CtObj['name'];
	}								
								
	$talkto1 = $chat_ds->where('littleuid='.$uid )->Distinct(true)->field('biguid')
								->order('speaktime desc')->limit($step)->select();	
	foreach ($talkto1 as $k => $v)
	{
		if($v['biguid'] > 100000000)
		{
			$CtObj = $doctor_ds->where('id='.$v['biguid'])->find();
		}
		else
		{
			$CtObj = $user_ds->where('id='.$v['biguid'])->find();	
		}
		$chatObj[$k]['uid'] = $v['biguid'];
		$chatObj[$k]['objName'] = $CtObj['name'];
		//$chatObj[$k]['speaktime'] = $v['speaktime']*1000;// distinct 后拿不到这个值??
	}									
	

    $this->echoJson(array('result' => 0, 'chatobj' => $chatObj)); 								
} 
*/
//加入群组聊天后的改造: 
//查找聊过天的人或群组 (聊天列表)
//http://121.40.78.46/tb/index.php?m=Home&c=App&a=searchChatObj&uid=9
//uid:病人id或医生id
//由于函数 searchChatObj 调用频繁，应该把 objName 保留在这个表中。别处修改时，同步修改这里。
 public function searchChatObj()
{
    $uid = intval(I('request.uid'));
	$chatlist_ds = D('Chatlist');  
	$chat = D('Chat');
        $user=D('User');
	$chatObj = $chatlist_ds->where('myuid=' .$uid)->order('speaktime desc')->select();							
	foreach ($chatObj as &$v){
                $v['speaktime'] = $v['speaktime'] *1000;
                //显示最后一条
                if($v['uid']==-1||$v['uid']==0){
                    $res=$chat->where("groupid=".$v['groupid'])->order('speaktime desc')->limit(0,1)->find();
                    
                    if(!$res){
                        $v['last_name']='';
                        $v['last_content']='';
                        
                    }else{
                        $u=$user->where('id='.$res['speakuid'])->find();
                        $v['last_name']=$u['name'];
                        $v['last_content']=$res['message'];
                        
                    }
                }else{
                    if($v['uid']>$v['myuid']){
                       $where="littleuid=".$v['myuid']." and biguid=".$v['uid']; 
                    }else{
                       $where="littleuid=".$v['uid']." and biguid=".$v['myuid'];  
                    }
                    $res=$chat->where($where)->order('speaktime desc')->limit(0,1)->find();
                    if(!$res){
                        $v['last_name']='';
                        $v['last_content']='';
                        
                    }else{
                        $u=$user->where('id='.$res['speakuid'])->find();
                        $v['last_name']=$u['name'];
                        $v['last_content']=$res['message'];
                        
                    }
                }
                if($v['uid']>0&&$v['uid']<100000000){
                    $rr=$user->where('id='.$v['uid'])->find();
                    if($rr['image']!=null){
                        $v['img']="http://img.user.ivf-bb.com/".rtrim($rr['image'],',');
                    }else{
                        $v['img']='no';
                    }
                }else if($v['uid']>100000000){
                    $doc=D("Doctor");
                    $rr=$doc->where('id='.$v['uid'])->find();
                    if($rr['img']!=null){
                        $v['img']='http://img.cndoc.ivf-bb.com/'.$rr['img'];
                    }else{
                        $v['img']='no';
                    }
                }else{
                    $v['img']='no';
                }
                unset($v['id']); 
                unset($v['myuid']); 
	}	
/*	
	$chat_ds = D('chat');   
	$user_ds = D('User');
	$doctor_ds = D('Doctor');
	$groupchatid_ds = D('groupchat_id');  
	
	$step = 50;
	
	$chatObj =array();
	
	//1.自己是大号，直接把更小的号取出即可。
	$talkto1 = $chat_ds->where('biguid=' .$uid)->Distinct(true)->field('littleuid')
								->order('speaktime desc')->limit($step)->select();
								
								
     //取需要的字段，放入 chatObj: 	
	foreach ($talkto1 as $k => $v)
	{
		$chatObj[$k]['uid'] = $v['littleuid'];//聊天对象uid
		
		//查名字
		$CtObj = $user_ds->where('id='.$v['littleuid'])->find();
		//$chatObj[$k]['groupid'] = '-1';		
		$chatObj[$k]['objName'] = $CtObj['name'];//聊天对象登录名。
		
		//再查一把时间: 
		$one = $chat_ds->where('littleuid=' .$v['littleuid'])
									->order('speaktime desc')->limit(1)->find();			
		$chatObj[$k]['speaktime'] = $one['speaktime']*1000;//取最新聊天时间
		
	}
	
	//2.(认为)自己是小号，可以取出大号和群聊(只能取自己发过言的群聊??)。
	$talkto1 = $chat_ds->where('littleuid='.$uid )->Distinct(true)->field('groupid,biguid')
								->order('speaktime desc')->limit($step)->select();

//$this->echoJson(array('result' => 0, 'talkto1' => $talkto1)); 
//$myfilex = fopen("qqqq43.txt", "w") or die("Unable to open file!");	
//fwrite($myfilex, "\ntime=" . time());

								
	foreach ($talkto1 as $k => $v)
	{
		$chatObj[$k]['groupid'] = $v['groupid'];
		$chatObj[$k]['uid'] = $v['biguid'];	
		
	    if($v['groupid'] == '-1') //单人聊
		{
			if($v['biguid'] > 100000000)
			{
				$CtObj = $doctor_ds->where('id='.$v['biguid'])->find();
			}
			else
			{
				$CtObj = $user_ds->where('id='.$v['biguid'])->find();	
			}

			$chatObj[$k]['objName'] = $CtObj['name'];	

			//再查一把时间: 
			$one = $chat_ds->where('biguid=' .$v['biguid'])
										->order('speaktime desc')->limit(1)->find();			
			$chatObj[$k]['speaktime'] = $one['speaktime']*1000;//取最新聊天时间			
		}
		else  //群聊
		{  //$dd = 5;
		   //fwrite($myfilex, "\ngroupid==" . $v['groupid']);
			$group  = $groupchatid_ds->where('groupchat_id=' .$v['groupid'])->find();
			$chatObj[$k]['objName'] = $group['groupname'];		

			//再查一把时间: 
			$one = $chat_ds->where('groupid=' .$v['groupid'])
										->order('speaktime desc')->limit(1)->find();			
			$chatObj[$k]['speaktime'] = $one['speaktime']*1000;//取最新聊天时间				
		}

	}		
	
	//fclose($myfilex);
	
	*/

    $this->echoJson(array('result' => 0, 'chatobj' => $chatObj)); 								
								
} 
//======================================================================================================	
//内部函数
    protected function echoJson($arr){
    	echo json_encode($arr);
    }
	


//上传图片。用户修改头像，或者发帖子，或者完成医嘱时附图。
//http://121.40.78.46/tb/index.php?zz=aaa&m=Home&c=App&a=uploadfile&type=xx&uid=5
//type:1=头像, 2=bbs附图,3病人完成医嘱时附图,4聊天附图,5聊天声音。
//uid:病人或医生id
	public function uploadfile()
    {
//		$uptypes=array(  
//			'image/jpg',  
//			'image/jpeg',
//			'image/pjpeg',
//			'image/png', 	
//			'image/bmp',
//			'image/gif',
//			'audio/amr',
//		); 
                $setting=C('UPLOAD_SITEIMG_QINIU');
                
//		$max_file_size=500000000000000;     //2M,上传文件大小限制, 单位BYTE   
		$type = intval(I('request.type'));
		$uid = intval(I('request.uid'));
		if($type==1) //头像
		{
                    $setting['driverConfig']['domain']='img.user.ivf-bb.com';
                    $setting['driverConfig']['bucket'] = 'imageuser';
//			$destination_folder="./imageUser/"; //用户头像图片路径 
		}
		else if($type==2) //bbs中加图片
		{
                    $setting['driverConfig']['domain']='bbsimg.ivf-bb.com';
                    $setting['driverConfig']['bucket'] = 'imagebbs';
//		    $destination_folder="./imageBBS/"; //BBS图片路径 
		}		
		else if($type==3) //病人完成医嘱时，可能需要提交图片
		{
                    $setting['driverConfig']['domain']='img.other.ivf-bb.com';
                    $setting['driverConfig']['bucket'] = 'imageother';
                    $setting['subName'] = 'imageDctAdvice/'.date('Y-m-d',time());
//		    $destination_folder="./imageDctAdvice/";  
		}
		else if($type==4 || $type==5 ) //聊天图片,声音
		{
                    $setting['driverConfig']['domain']='chat.img.ivf-bb.com';
                    $setting['driverConfig']['bucket'] = 'imagechat';
//		    $destination_folder="./imageChat/";  
		}
                
		$Upload = new \Think\Upload($setting);
                $info = $Upload->upload($_FILES);
                

                $t=  date('Y-m-d',time());
                $name='';
                foreach ($info as $v){
                    $name.=$t.'/'.$v['savename'].',';
                }
                if($type==1)  //头像
		{
			if($uid > 100000000 )
			{
			    $DB = D('Doctor');
			}
			else
			{
			    $DB = D('User');
			}
			
            $result1 = $DB->where('id='.$uid)->setField('image', $name);			
		}
		else
		{
			//实在没有办法，只好写数据库了
			$temp_info = D('temp_info'); 
			$data['uid'] = $uid ;
			$data['attach'] = $name;
			$data['time'] =  date('Y-m-d H:i:s',time());
			$data['expire_time'] = time()+30;//30秒失效,一般几秒内应有下一个调用来接收这个附件。
			
			if($type==4 || $type==5)
			{
			    $data['attach'] = "http://chat.img.ivf-bb.com/" . $t.'_'.$info[key($_FILES)]['savename'];
			}			
			$temp_info->add($data);			
		}
		$this->echoJson(array('result' => 0, 'uploadfile' => 'OK')); 
	//return 201;
    }
//=====================================================================================
//增加群聊对象。第一次增加时，服务器需要插入群id
//仿照微信: 用户a在跟用户b聊天时，把用户c拉进来，此时会形成一个群。这时调用: 
//http://121.40.78.46/tb/index.php?m=Home&c=App&a=addgroupChatobject&groupid=-1&objectid=a;b;c
//此后群内任何人拉朋友进群时，调用: 
//http://121.40.78.46/tb/index.php?m=Home&c=App&a=addgroupChatobject&groupid=6&objectid=4  
//groupid:聊天室id,第一次加人时传入-1,此时，objectid 是三个人的id，分号隔开
//objectid:聊天对象（用户或医生）的id，即被拉入群的人的id
//简单起见，与人聊天或拉人入群，不需要对方同意。直接就说话了。
	public function addgroupChatobject()
    {
$myfilex = fopen("qq-addgroupChatobject.txt", "w") or die("Unable to open file!");	
		
		$groupid=I('request.groupid');
		$userdoctor_id=I('request.objectid');
fwrite($myfilex, "\ngroupid=" .$groupid);
fwrite($myfilex, "\nuserdoctor_id=" .$userdoctor_id);
		
		$groupchat_id_ds = D('groupchat_id');
		$user_ds = D('User');
		$doctor_ds = D('Doctor');	
		$chatlist_ds = D('chatlist');		
		
		if($groupid == -1 || $groupid==0)//第一次，建立群.
		{
			$data['userdoctor_ids'] = ";" .$userdoctor_id . ";" ;	//前后加上分号		

			//拼群组名称: 
			$groupname = '群:';			            
			$speakeridarr = explode(";",$userdoctor_id);
			$ii=0;
		
			foreach ($speakeridarr as $speakerid)
			{			
				$ii = $ii+1;
				if($ii>4){break;} //最多4个。
				if($speakerid > 100000000)
				{
					$CtObj   = $doctor_ds->where('id='.$speakerid)->find();					
				}
				else
				{
					$CtObj   = $user_ds->where('id='.$speakerid)->find();						
				}
				$groupname = $groupname .$CtObj['name']. "," ;
			}	//for	
			$data['groupname'] = $groupname;//最后还有个逗号，算了。
			
			$groupchat_id = $groupchat_id_ds->add($data);	
			
			foreach ($speakeridarr as $speakerid)
			{		
				/*
				if($speakerid > 100000000)
				{
					$CtObj   = $doctor_ds->where('id='.$speakerid)->find();
					
					$newids  = $CtObj['groupchatids'] . $groupchat_id  . ";" ;	
					$result1 = $doctor_ds->where('id='.$speakerid)->setField('groupchatids', $newids);						
				}
				else
				{
					$CtObj   = $user_ds->where('id='.$speakerid)->find();	

					$newids  = $CtObj['groupchatids'] . $groupchat_id  . ";" ;	
					$result1 = $user_ds->where('id='.$speakerid)->setField('groupchatids', $newids);						
				}
				//$groupname = $groupname .$CtObj['name']. "," ;	*/	
                                $chatlistr['myuid']	=$speakerid;
				$chatlistr['groupid']	=$groupchat_id;
				$chatlistr['uid']	= -1;
				$chatlistr['objName']	=$groupname;
				$chatlistr['speaktime']	=time();
				$chatlist_ds->add($chatlistr);				
			}	//for			
 	
			$this->echoJson(array('result' => 0, 'groupchat_id' => $groupchat_id, 'groupname' => $groupname));
		}
		else  //群早已存在
		{
		    //在群组表里增加聊天人id
			$rec     = $groupchat_id_ds->where('groupchat_id='.$groupid)->find();
			$newids  = $rec['userdoctor_ids']  . $userdoctor_id . ";";			

			$result1 = $groupchat_id_ds->where('groupchat_id='.$groupid)->setField('userdoctor_ids', $newids);
			
			
			//对个人，记录群id
			/*			
		    $rec     = $user_ds->where('id='.$userdoctor_id)->find();
			$newids  = $rec['groupchatids'] . $groupid  . ";" ;	
			$result1 = $user_ds->where('id='.$userdoctor_id)->setField('groupchatids', $newids);
			*/			
			$chatlistr['myuid']	=$userdoctor_id;
			$chatlistr['groupid']	=$groupid;
			$chatlistr['uid']	= -1;
			$chatlistr['objName']	=$rec['groupname'];
			$chatlistr['speaktime']	=time();
			$chatlist_ds->add($chatlistr);			
			$groupname = $rec['groupname'];//就这样吧。不再追加人名了。
		    $this->echoJson(array('result' => 0, 'groupchat_id' => $groupid, 'groupname' => $groupname));
		} //else
//fclose($myfilex);		
	}
	
//=====================================================================================
	//用户关注/取消关注某医生
	//http://121.40.78.46/tb/index.php?m=Home&c=App&a=userAttentionDoctor&attention=0&uid=1&doctorid=100000001
	//attention: int， =0取消关注，=1关注
	//uid: 病人id
	//doctorid: 医生id
	public function userAttentionDoctor()
    {
    	$attention = intval(I('request.attention'));
		$userid    = intval(I('request.uid'));
    	$doctorid  = intval(I('request.doctorid'));
		
		$attention_doctor_ds = D('attention_doctor');
		$doctor_ds = D('Doctor');
		if($attention == 0) //取消关注
		{
            $attention_doctor_ds->where("userid=".$userid." and doctorid=" . $doctorid)->delete();
			$doctor_ds->where('id='.$doctorid)->setDec('haoping_cnt', 1);
		}
		else
		{
			$att = $attention_doctor_ds->where("userid=".$userid." and doctorid=" . $doctorid)->find();
			if ($att == null)
			{
				$data['userid'] = $userid;
				$data['doctorid'] =$doctorid;	
				$attention_doctor_ds->add($data);
			}		
			$doctor_ds->where('id='.$doctorid)->setInc('haoping_cnt', 1);
		}
		//$this->echoJson(0);
		$this->echoJson(array('result' => 0, 'userAttentionDoctor' => $groupid));
	}    
	//=====================================================================================
	//获取用户关注的医生列表
	//http://121.40.78.46/tb/index.php?m=Home&c=App&a=myAttentionDoctorList&uid=1
	//uid: 病人id
	public function myAttentionDoctorList()
        {
		$userid    = intval(I('request.uid'));
		
		$attention_doctor_ds = D('attention_doctor');
		$doctor_ds = D('Doctor');
		
        $attDoctors = $attention_doctor_ds->where("userid=".$userid)->select();
    	//$attDoctors = array();		
    	foreach ($attDoctors as $k => $v){
    		$doctor = $doctor_ds->where('id='.$v['doctorid'])->find();
    		$attDoctors[$k]['doctorname'] = $doctor['name'];
                if($doctor['img']!=null){
                        $attDoctors[$k]['doctorimg']='http://img.cndoc.ivf-bb.com/'.$doctor['img'];
                    }else{
                        $attDoctors[$k]['doctorimg']='';
                    }
    		unset($attDoctors[$k]['userid']);  		
    	}
		
    	$this->echoJson(array('result' => 0, 'attDoctors' => $attDoctors));
	}     
	//=====================================================================================
	//用户申请增加/去除 我的医生
	//http://121.40.78.46/tb/index.php?m=Home&c=App&a=addMyDoctor&adddel=0&uid=1&doctorid=10001
	//adddel: =0删除，=1增加为我的医生
	//uid: 病人id
	//doctorid: 医生id	
	public function addMyDoctor()
    {
    	$adddel = intval(I('request.adddel'));
		$userid    = intval(I('request.uid'));
    	$doctorid  = intval(I('request.doctorid'));
		
		$heartbeatmsg_ds = D('heartbeat_msgtable');		
		$my_doctor_ds = D('my_doctor');
		
		if($adddel == 0) //删除
		{
			$my_doctor_ds->where("userid=".$userid." and doctorid=" . $doctorid)->delete();	
		}
		else //我的医生 
		{
			$mydoc = $my_doctor_ds->where("userid=".$userid." and doctorid=" . $doctorid)->find();
			if ($mydoc == null)
			{
				$data['userid'] = $userid;
				$data['doctorid'] =$doctorid;	
				$my_doctor_ds->add($data);
			}			
		}  
		
		$data2['uid'] = $doctorid;
		$data2['msgid'] ='1';
		$data2['todo'] ='Dct_NeedMyConfirmMyDoctor';		
		$data2['time'] =time();				
		$heartbeatmsg_ds->add($data2);
				
		//$this->echoJson(0);
		$this->echoJson(array('result' => 0, 'addMyDoctor' => $groupid));
	}    
	//=====================================================================
	//获取我的医生列表
	//http://121.40.78.46/tb/index.php?m=Home&c=App&a=myDoctorList&uid=1
	//uid: 病人id
	public function myDoctorList()
    {
		$userid    = intval(I('request.uid'));
		
		$my_doctor_ds = D('my_doctor');
		$doctor_ds = D('Doctor');
                $hospital=D("Hospital");
//$myfilex = fopen("qq-myDoctorList.txt", "w") or die("Unable to open file!");	
//fwrite($myfilex, "\nuserid=" .$userid);

		
        $myDoctors = $my_doctor_ds->where("userid=".$userid . ' and doc_confirm=1'  )->select();
		//$myDoctors = $my_doctor_ds->where("userid=".$userid  )->select();	
        foreach ($myDoctors as $k => $v){
               
    		$doctor = $doctor_ds->where('id='.$v['doctorid'])->find();
                if(!$doctor){
                    $this->echoJson(array('result' => 0, 'myDoctors' => ''));
                }
    		$myDoctors[$k]['doctorname'] = $doctor['name'];
                if($doctor['img']!=null){
                    $myDoctors[$k]['img'] = 'http://img.cndoc.ivf-bb.com/'.$doctor['img'];
                }else{
                    $myDoctors[$k]['img']='';
                }
               
                $rr=$hospital->where("id=".$doctor['hospital_id'])->find();
                if(!$rr){
                    $this->echoJson(array('result' => 0, 'myDoctors' => ''));
                }
                $myDoctors[$k]['hos'] = $rr['name'];
    		unset($myDoctors[$k]['userid']); 
		unset($myDoctors[$k]['doc_confirm']);// doc_confirm 必须全小写 			
    	}
//fclose($myfilex);		
    	$this->echoJson(array('result' => 0, 'myDoctors' => $myDoctors));
	}  
	//=====================================================================
	//医生端获取我的病人列表
	//http://121.40.78.46/tb/index.php?m=Home&c=App&a=Dct_myPatientList&doctorid=100000002
	//doctorid:医生id
	public function Dct_myPatientList()
    {
		$doctorid    = intval(I('request.doctorid'));
		
		$my_doctor_ds = D('my_doctor');
		$user_ds = D('User');
		
        $myPatients = $my_doctor_ds->where("doctorid=".$doctorid . ' and doc_confirm=1'  )->select();
			
    	foreach ($myPatients as $k => $v){
    		$patient = $user_ds->where('id='.$v['userid'])->find();
    		$myPatients[$k]['patientname'] = $patient['name'];
                if($patient['image']!=null){
                    $myPatients[$k]['img'] = "http://img.user.ivf-bb.com/".rtrim($patient['image'],",");
                }else{
                    $patient['image']='';
                }
    		unset($myPatients[$k]['doctorid']); 
		unset($myPatients[$k]['doc_confirm']);			
    	}
		
    	$this->echoJson(array('result' => 0, 'myPatients' => $myPatients));
	} 	
	
	//医生:用户申请了一个医生为“我的医生”，需要医生确认同意。本接口就是获取到这个申请(列表)，待医生确认。
	//http://121.40.78.46/tb/index.php?m=Home&c=App&a=Dct_NeedMyConfirmMyDoctor&doctorid=100000002
	//doctorid:医生id
	public function Dct_NeedMyConfirmMyDoctor()
    {
    	$doctorid  = intval(I('request.doctorid'));
		
		$my_doctor_ds = D('my_doctor');
		$user_ds = D('User');
		
        $NeedConfirmUsers = $my_doctor_ds->where("doctorid=".$doctorid . ' and doc_confirm=0'  )->select();
			
    	foreach ($NeedConfirmUsers as $k => $v){
    		$user = $user_ds->where('id='.$v['userid'])->find();
    		$NeedConfirmUsers[$k]['username'] = $user['name'];
                if($user['image']!=null){
                    $NeedConfirmUsers[$k]['img'] = "http://img.user.ivf-bb.com/".rtrim($user['image'],",");
                }else{
                    $NeedConfirmUsers[$k]['img']='';
                }
    		unset($NeedConfirmUsers[$k]['doctorid']); 
			unset($NeedConfirmUsers[$k]['doc_confirm']);		
    	}
		
    	$this->echoJson(array('result' => 0, 'NeedConfirmUsers' => $NeedConfirmUsers));
	} 	
	//医生动作: 确认用户的申请“我的医生”，。
	//http://121.40.78.46/tb/index.php?m=Home&c=App&a=Dct_DoctorConfirmMyDoctor&uid=1&doctorid=100000002
	//uid:病人id
	//doctorid: 医生id
	public function Dct_DoctorConfirmMyDoctor()
    {
		$userid    = intval(I('request.uid'));
    	$doctorid  = intval(I('request.doctorid'));
		
		$my_doctor_ds = D('my_doctor');
		$result1 = $my_doctor_ds->where("userid=".$userid." and doctorid=" . $doctorid)->setField('doc_confirm', 1);
		
		//记录消息--待通知用户端。
        $heartbeatmsg_ds = D('heartbeat_msgtable');
		$data['uid'] = $userid;
		$data['msgid'] ='2';
		$data['todo'] ='myDoctorList';		
		$data['time'] =time();				
		$heartbeatmsg_ds->add($data);		
		$this->echoJson(array('result' => 0, 'Dct_DoctorConfirmMyDoctor' => $groupid));
	} 
	
	
	//病人端医生端同用: 获取医生发给病人的医嘱(多条目）。
	//http://121.40.78.46/tb/index.php?m=Home&c=App&a=getMyDoctorAdvice&uid=1
	//uid:病人id. 医生端用时也是传入病人id
	public function getMyDoctorAdvice()
        {
		$userid    = intval(I('request.uid'));
    	//$doctorid  = intval(I('request.doctorid'));
		//$doctor_ds = D('Doctor');		
		
		$doctoradvice_ds = D('doctoradviceAction');
		$advices = $doctoradvice_ds->where("userid=".$userid)->order('fromtime')->select();
		
    	foreach ($advices as $k => $v){
            if($v['attach']!=null){
                $arr= explode(",",rtrim($v['attach'],","));
                foreach($arr as &$vv){
                    $vv="http://img.other.ivf-bb.com/imageDctAdvice/" . $vv;
                }
                $advices[$k]['attach']=$arr;
            }
                if($v['doctorid']>100000000){
                    $Doctor=D("Doctor");
                    $r=$Doctor->where("id=".$v['doctorid'])->find();
                    $advices[$k]['name']=$r['name'];
                }else{
                    $User=D("User");
                    $rr=$User->where("id=".$userid)->find();
                    $advices[$k]['name']=$rr['name'];
                }
    		//$doctor = $doctor_ds->where('id='.$v['doctorid'])->find();
    		//$advices[$k]['doctorname'] = $user['name'];
			//$advices[$k]['fromtime'] = $advices[$k]['fromtime']*1000;
			//$advices[$k]['totime']   = $advices[$k]['totime']*1000;
    		unset($advices[$k]['userid']); 
			unset($advices[$k]['steptypeid']);		
    	}
		
    	$this->echoJson(array('result' => 0, 'advices' => $advices));	
	} 	
	
	//病人端/医生端同用: 增加/删除/改,医嘱(条目)。(病人端没有增/删；修改可能也要受限)
	//http://121.40.78.46/tb/index.php?m=Home&c=App&a=OperateDoctorAdvice&id=-1&uid=6&doctorid=100000001&fromtime=xx&totime=yyy&steptypeid=zz&stepname=kk&drug=dd&howmuch=hh  //医生-新增,steptypeid/drug/howmuch可选
	//http://121.40.78.46/tb/index.php?m=Home&c=App&a=OperateDoctorAdvice&id=5&fromtime=xx&totime=yyy&steptypeid=zz&stepname=kk&drug=dd&howmuch=hh     //医生/病人-修改,steptypeid/drug/howmuch可选
	//http://121.40.78.46/tb/index.php?m=Home&c=App&a=OperateDoctorAdvice&id=5&op=del  //医生-删除
	//id : int, 医嘱条目id，-1时为新增。否则为修改或删除
	//uid:int, 病人id
	//doctorid:int, 医生id
	//fromtime:开始时间，字符串，形如“2015-06-09 12:24”，可以不要时间部分
	//totime:结束时间，字符串，形如“2015-06-09 12:24”，可以不要时间部分
	//steptypeid:int, 步骤类型id，1-7？暂未用。
	//stepname:字符串，步骤名称，如: 打针/吃药	
	//drug:字符串，药品名称:
	//howmuch: 字符串，药品用量，如 0.5mg	
	//可修改内容: 开始时间，结束时间，步骤id/步骤名称，药品，用量
	public function OperateDoctorAdvice()
    {
		$op = I('request.op', '');
		$id    = intval(I('request.id'));
		$doctoradvice_ds = D('doctoradvice');
		$doctoradvice_action_ds = D('doctoradvice_action');
		
		if($op == 'del') //删除 ??需要控制，已完成的不让删
		{
		    $doctoradvice_action_ds->where('adviceid='.$id . ' and f_finished=0')->delete();
			$finish = $doctoradvice_action_ds->where('adviceid='.$id )->select();
			if($finish == null) //没有已完成的action，则允许删除医嘱。
			{
			    $doctoradvice_ds->where('id='. $id)->delete(); 
			}
			
			//return 0;
			$this->echoJson(array('result' => 0, 'del' => 'OK'));
			exit;
		}
	
		$userid    = intval(I('request.uid'));
		$doctorid  = intval(I('request.doctorid'));
		$fromtime  = date('Y-m-d H:i:m',strtotime(I('request.fromtime')));//I('request.fromtime');//这里转换一下，是为了把客户端传来的日期格式补上0，如2011-9-3补成2011-09-03
		$totime    = date('Y-m-d H:i:m',strtotime(I('request.totime')));//I('request.totime');//补0了后面好判断相等。
		
		if($fromtime > $totime) //客户端竟然没有判断。好吧。换个位置继续。
		{
		   $tt = $fromtime;
		   $fromtime = $totime;
		   $totime = $tt;
		}
		
		$steptypeid    = intval(I('request.steptypeid'));
		$stepname = I('request.stepname', '');
		$drug = I('request.drug', '');
		$howmuch = I('request.howmuch', '');
			$data['userid'] = $userid;
			$data['doctorid'] = $doctorid;
			$data['fromtime'] = $fromtime;
			$data['totime'] = $totime;			
			$data['steptypeid'] = $steptypeid;
			$data['stepname'] = $stepname;
			$data['f_steptodo'] = '1';//生效
			$data['drug'] = $drug;
			$data['howmuch'] = $howmuch;
			
//*			
$myfilex = fopen("qq-OperateDoctorAdvice.txt", "w") or die("Unable to open file!");	
fwrite($myfilex, "\nfromtime=" . $data['fromtime']);
fclose($myfilex);	
//*/
			
		//新增，或修改，都会产生一条新的医嘱: 	
		$adviceid = $doctoradvice_ds->add($data);
		$data['adviceid'] = $adviceid;
		if($data['stepname']=='DA_injection' || $data['stepname']=='DA_medicine') //每天复制一条。
		{
			$endtime = $data['totime'];//记录结束时间;
		
			$data['totime'] = $data['fromtime'];
			$doctoradvice_action_ds->add($data);
				$kk = 0;
				
			$datex = strtotime($data['fromtime']);	
			while($data['totime'] != $endtime)
			{
				$datex = strtotime('+1 Day',$datex); //$b_time = strtotime('+5 Month',$a_time);
				$data['fromtime']= date('Y-m-d H:i:m',$datex); //$b = date('Y-m-d H:i:s',$b_time);
				$data['totime'] = $data['fromtime'];			
				$doctoradvice_action_ds->add($data);	
					$kk =$kk +1;
					if($kk>50) break;//以防万一				
			}		
		}	
		else //其它，复制一条。
		{
			$doctoradvice_action_ds->add($data);
		}		
			

			
		if($id == -1) //新增
		{	
                        $this->Jpush("有医生对你下医嘱了!",array('tag'=>array("$userid")));
			//return $adviceid;
			$this->echoJson(array('result' => 0, 'OperateDoctorAdvice' => 'OK'));
			exit;
		}
		
		//修改:
		/*
		if($data['userid'] == 0) unset($data['userid']);//不可能修改
		if($data['doctorid'] == 0) unset($data['doctorid']);//不可能修改
		if($data['fromtime'] == '') unset($data['fromtime']);
		if($data['totime'] == '') unset($data['totime']);
		if($data['steptypeid'] == 0) unset($data['steptypeid']);
		if($data['stepname'] == '') unset($data['stepname']);
		if($data['drug'] == '') unset($data['drug']);
		if($data['howmuch'] == '') unset($data['howmuch']);		
		
		$doctoradvice_ds->where('id=' .$id)->save($data);	
		//$this->echoJson(array('result' => 0, 'advices' => $advices)) ;	
		*/
    	$doctoradvice_action_ds->where('adviceid='.$id . ' and f_finished=0')->delete();
		$this->echoJson(array('result' => 0, 'OperateDoctorAdvice' => 'OK'));
	} 		
	//==================================================================================
	//病人完成一个步骤后，点击“完成”，并通知到医生端。
	//一般: http://121.40.78.46/tb/index.php?m=Home&c=App&a=finish_advice&uid=6&adviceid=1&feedback=xxx
	//B超: http://121.40.78.46/tb/index.php?m=Home&c=App&a=finish_advice&uid=6&adviceid=1&leftovary=分号分隔的结果串&rightovary=分号分隔的结果串&feedback=xxx
	//分号分隔的结果串，形如: 1*1;2*2;3*3;4*4;5*5;6*6;7*7;8*8
	//验血:http://121.40.78.46/tb/index.php?m=Home&c=App&a=finish_advice&uid=6&adviceid=1&blood=分号分隔的结果串2&feedback=xxx
	//分号分隔的结果串2:形如: 1;2;3;4;5;6
	//uid:病人id
	//id:医嘱的id，修正: 是医嘱下面一个动作的id
	public function finish_advice()
	{
		$uid    = intval(I('request.uid'));
		$id  = intval(I('request.id'));
		$feedback  = I('request.feedback');
		$doctoradvice_action_ds = D('doctoradvice_action');
		
		$doctoradvice_action_ds->where('id=' .$id)->setField('f_finished', 1);//不要使用 tinyint，否则会偶然错误。	
		$doctoradvice_action_ds->where('id=' .$id)->setField('finishtime', time());
        $doctoradvice_action_ds->where('id=' .$id)->setField('feedback', $feedback);		
		//$data['f_finished'] ='1';
		//$data['finishtime'] =time();
		//$doctoradvice_action_ds->where('id=' .$adviceid)->save($data);
		
		$advice = $doctoradvice_action_ds->where('id=' .$id)->find();
		if($advice == null) //几乎不可能出现
		{
		    $this->echoJson(array('result' => 1, 'finish_advice' => '无此id'));
			exit;
		}

		
        $temp_info = D('temp_info'); 
		$atta =  $temp_info->where('uid='. $uid)->find(); 
		if($atta != null) //这个用户有提交图片。
		{
			$doctoradvice_action_ds->where('id=' .$id)->setField('attach', $atta['attach']);
			$temp_info->where('uid='. $uid)->delete();		
		}
	 
		//if($advice['steptypeid'] == xx )
		if($advice['stepname'] == 'DA_bultra' ) //B超。
		{
		    $result1 = I('request.leftovary');
			$result2 = I('request.rightovary');
			$doctoradvice_action_ds->where('id=' .$id)->setField('result1', $result1);
			$doctoradvice_action_ds->where('id=' .$id)->setField('result2', $result2);			
		}
		else if($advice['stepname'] == 'DA_bloodtest' ) //验血
		{
			$result1 = I('request.blood');//$prl . ';' .$fsh . ';' .$lh . ';' .$prge . ';' .$tsto . ';' .$ee2; 
			
			$doctoradvice_action_ds->where('id=' .$id)->setField('result1', $result1);
		}		
			
		$doctorid = $advice['doctorid'];
		$heartbeatmsg_ds = D('heartbeat_msgtable');
		$data2['uid'] = $doctorid;
		$data2['msgid'] ='3';
		$data2['todo'] ='Dct_getfinishedadvice';		
		$data2['time'] =time();				
		$heartbeatmsg_ds->add($data2);
                $this->Jpush("有病人完成了医嘱中的一个步骤,请查看!",array('tag'=>array($doctorid)),"doctor");
        $this->echoJson(array('result' => 0, 'finish_advice' => 'OK'));
		
	}
	//==================================================================================
	//医生端获取病人完成的一个步骤(打针/吃药等)，简单查看一下，用于决定下一步。
	//本函数查询此医生所有病人的完成步骤，按时间列出
	//http://121.40.78.46/tb/index.php?m=Home&c=App&a=Dct_getfinishedadvice&doctorid=100000001
	//doctorid:医生id
	//输出参数:
	//f_finished:0未完成，1完成，2完成并且医生已读。
	//finishtime: int,完成时间。
	//attach: URL组,病人上传的医嘱所附图片。
	//应改名为 Dct_getfinishedadvice_action
	public function Dct_getfinishedadvice()
	{
		$doctorid    = intval(I('request.doctorid'));

		$doctoradvice_action_ds = D('doctoradvice_action');
		$recs =$doctoradvice_action_ds->where('doctorid=' .$doctorid . ' and f_finished != 0')->order("finishtime")->select();
        $user_ds = D('User');		
    	foreach ($recs as $k => $v){
            if($v['attach']!=null){
                $arr= explode(",",rtrim($v['attach'],","));
                foreach($arr as &$vv){
                    $vv="http://img.other.ivf-bb.com/imageDctAdvice/" . $vv;
                }
                $recs[$k]['attach']=$arr;
            }
		    $user = $user_ds->where('id=' .$recs[$k]['userid'])->find();
			$recs[$k]['username'] = $user['name'];
			$recs[$k]['finishtime'] = $recs[$k]['finishtime']*1000;
    		unset($recs[$k]['doctorid']);
			unset($recs[$k]['f_steptodo']);			
            //unset($recs[$k]['f_finished']); 0未完成，1完成，2医生已阅读。
			
			if($user['image'] != null)
			{
				
				 $recs[$k]['image']= "http://img.user.ivf-bb.com/" . rtrim($user['image'],",");
				
			}	

			//if($recs[$k]['steptypeid'] == xx)
			if($recs[$k]['stepname'] == 'DA_bultra') //B超
			{
				$recs[$k]['leftovary'] = $recs[$k]['result1'];
				$recs[$k]['rightovary'] = $recs[$k]['result2'];
			}
			else if($recs[$k]['stepname'] == 'DA_bloodtest')//验血
			{
				$recs[$k]['blood'] = $recs[$k]['result1'];
			}	
			unset($recs[$k]['result1']);
			unset($recs[$k]['result2']);			
			
    	}   		
		
		
	    $this->echoJson(array('result' => 0, 'finishedadvices' => $recs));	
	}	
	//==================================================================================
	//医生动作，设置（用户已完成医嘱）为已读状态。
	//http://121.40.78.46/tb/index.php?m=Home&c=App&a=Dct_setFinishedAdviceReaded&adviceid=5
	//adviceid:int, 医嘱id
	public function Dct_setFinishedAdviceReaded()
	{
		$adviceid    = intval(I('request.adviceid'));
		$doctoradvice_action_ds = D('doctoradvice_action');
		$doctoradvice_action_ds->where('id=' .$adviceid)->setField('f_finished', 2);	
		$this->echoJson(array('result' => 0, 'Dct_setFinishedAdviceReaded' => 'OK'));
	}	
	
	//==================================================================================
	//终端"获取验证码",服务器生成/发送到手机号码,用于未登录之前的重置密码，或者注册时。
	//http://121.40.78.46/tb/index.php?m=Home&c=App&a=getCAPTCHA&telephone=18964640313&type=2
	//type: 1=注册时，2重置密码时。
	//本函数存在一点点小问题，有时可能引发bug: 以前每个手机号绑定唯一ID号，就是系统中每个手机号唯一。现在多个ID可以绑定同一
	//手机号，但在发送验证码时，只有手机号，会导致多个ID号的 CAPTCHA 被修改。如果两个ID同时修改，就会乱套。当然问题不大，因为
	//一个手机号只对应同一个人，一般不会同时登录两个ID。
	public function getCAPTCHA()
	{
		$phone = I('request.telephone');
		$type = I('request.type');
		//$CAPTCHA = rand(100000,9999999);
		$CAPTCHA = rand(1000,9998);
		
		$who = I('request.who');
		
		if($type == 1) //注册,//写临时表
		{  
                        $user_ds = D('User');
			$r1 = $user_ds->where('telephone='.$phone)->find();
                        if(isset($r1)){
                            $this->echoJson(array('result' => 1, 'info' => "手机号已注册"));exit;	
                        }
                        $temp_info = D('temp_info'); 			
			$data['uid'] = $phone;
			$data['attach'] = $CAPTCHA;
			$data['time'] =  date('Y-m-d',time());
			$data['expire_time'] = time()+60;//300秒失效,短信接口比较慢，时间放长一点。
			
			$temp_info->add($data);	
                        $msg = "注册验证码：";			
		}
		else //忘记密码，需要重置
		{
                    
		    $user_ds = D('User');
                    $r = $user_ds->where("telephone='".$phone . "'")->find();
                    if(!$r){
                        $this->echoJson(array('result' => 1, 'info' => "该手机号未注册"));exit;
                    }
			$result1 = $user_ds->where('telephone='.$phone)->setField('CAPTCHA', $CAPTCHA);
			$msg = "密码重置验证码：";
		}
			
		
		//http://api.duanxin.cm/?action=send&username=70204978&password=b3d0afdfffcee05b512dafa798c6d004&phone=手机号&content=短信内容
		$content = $CAPTCHA;
		
/*		
两个接口现在都在报备运营商了
密码:  Qb456001
一个是专门发送验证码的:    70211594  key:  53a3dd3914869b9d5bb8046030026079
一个是专门发送营销短信的:  70210456  key:  53a3dd3914869b9d5bb8046030026079
两千万不要弄错了，不然那就完蛋了*/		
		
		//老的
if($who == 'pd')	//浦东科技
{	
		$username = '70204978';           //用户账号
			//$password = '18629013072';        //密码  这是真是密码，使用时请注意不要发送垃圾短信防止被封号
			//$password = strtolower(md5($password));
		$password = 'b3d0afdfffcee05b512dafa798c6d004';
}
else
{
		//新的
		$username = '70211594';           //用户账号.上次说的是  70211597
		    //$password = 'Qb456001';//'18516211962';        //密码没啥用。不相等的。
		//$password = '53a3dd3914869b9d5bb8046030026079';//strtolower(md5($password));
		$password = 'f307f407a99db037a1541701481a0208';
		
		//$username = '70210456';  
 }

		$http = 'http://api.duanxin.cm/?action=send&username='.$username.'&password='.$password.'&phone='.$phone.'&content='.urlencode( iconv('utf-8','gbk', $msg . $content) );
		$ch=curl_init();
		curl_setopt($ch,CURLOPT_URL,$http);
		curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
		$data = curl_exec($ch);
		curl_close($ch);
		
		//$this->echoJson(array('result' => 0, 'CAPTCHA' => '见手机短信'));	
		$this->echoJson(array('result' => 0, 'CAPTCHA' => $data));	
	}	

    //==================================================================================	
	//用户(病人或医生),用于(忘记密码)未登录之前的重置密码。
	//http://121.40.78.46/tb/index.php?m=Home&c=App&a=resetPassword&logtype=1&name=qqqq&telephone=13698765432&captcha=验证码&password=新密码
	//logtype:1为医生，否则（0，无，其它）为病人端。
	//name:登录名。
	public function resetPassword()
	{
    	$name= I('request.name');//登录帐号
    	$phone = I('request.telephone');
    	$password = I('request.password');
		$logtype = I('request.logtype');
		$passwordmd5 = md5($password);
		$captcha = I('request.captcha');		
		if(!preg_match('/^[_0-9a-z]{8,16}$/i',$password)){
			$this->echoJson(array('result' => 5, 'resetPassword' => "密码只能是字母、数字、下划线长度至少8位"));
			exit;
		}
		if($name=='' || $phone=='' || $password=='' )
		{
		    $this->echoJson(array('result' => 2, 'resetPassword' => '帐号电话密码都不能为空。'));exit;
		}
		
		if($logtype==1)
		{
		    $DB = D('Doctor');
			$theRec = $DB->where("telephone='".$phone . "' and logname='" .$name ."'")->find();
		}
		else
		{
			$DB = D('User');
			$theRec = $DB->where("telephone='".$phone . "'")->find();		
		}
		

		if($theRec == null)
		{
		    $this->echoJson(array('result' => 3, 'resetPassword' => '帐号或手机号错误，须匹配.'));
			return;
		}
		
		
		if($theRec['captcha'] == $captcha)
		{
			if($logtype==1)
			{
				$result1 = $DB->where("telephone='".$phone . "' and logname='" .$name ."'")->setField('password', $passwordmd5);
			}
			else
			{
				$result1 = $DB->where("telephone='".$phone . "'")->setField('password', $passwordmd5);		
			}		
		    
			$this->echoJson(array('result' => 0, 'resetPassword' => 'OK'));	
			return;
		}
		else
		{
		    $this->echoJson(array('result' => 1, 'resetPassword' => '验证码不正确'));	
			return;
		}	
		
		$this->echoJson(array('result' => 4, 'resetPassword' => '错误原因待查'));	
		return;		
	}
	//==================================================================================
	//用户(病人或医生)已登录状态下，修改密码: 	
	//http://121.40.78.46/tb/index.php?m=Home&c=App&a=modifyPassword&uid=100000005&password=新密码
	public function modifyPassword()
	{
		$uid = I('request.uid');
		$password = I('request.password');
		if(!preg_match('/^[_0-9a-z]{8,16}$/i',$password)){
			$this->echoJson(array('result' => 1, 'info' => "密码只能是字母、数字、下划线长度至少8位"));
			exit;
		}
		$passwordmd5 = md5($password);
	    if($uid < 100000000)
		{
			$user_ds = D('User');
			$result1 = $user_ds->where('id='.$uid)->setField('password', $passwordmd5);
                        $this->echoJson(array('result' => 0, 'info' => 'ok'));	
		}
		else
		{
			$doctor_ds = D('Doctor');
			$result1 = $doctor_ds->where('id='.$uid)->setField('password', $passwordmd5);
                        $this->echoJson(array('result' => 0, 'info' => 'ok'));	
		}				
	}	
	
			
	//病人端: 获取我的医嘱动作（打针或吃药这两种医嘱，每一条医嘱假设跨N天则有N个动作。其它医嘱每条一个动作）。
	//http://121.40.78.46/tb/index.php?m=Home&c=App&a=getMyDoctorAdviceAction&uid=1
	//uid:病人id. 
//	public function getMyDoctorAdviceAction()
//    {
//		$userid    = intval(I('request.uid'));
//    	//$doctorid  = intval(I('request.doctorid'));
//		//$doctor_ds = D('Doctor');		
//		
//		$doctoradvice_action_ds = D('doctoradvice_action');
//		$actions = $doctoradvice_action_ds->where("userid=".$userid)->order('fromtime')->select();
//		
//    	foreach ($actions as $k => $v){
//    		//$doctor = $doctor_ds->where('id='.$v['doctorid'])->find();
//    		//$actions[$k]['doctorname'] = $user['name'];
//			//$actions[$k]['fromtime'] = $actions[$k]['fromtime']*1000;
//			//$actions[$k]['totime']   = $actions[$k]['totime']*1000;
//    		unset($actions[$k]['userid']); 
//			unset($actions[$k]['steptypeid']);	
//
//			if($actions[$k]['attach'] != null)
//			{
//				$attachx = explode(",",$actions[$k]['attach']);
//				if(count($attachx) > 0)
//				{				
//					$attachOut = array();
//					foreach ($attachx as $aattach)
//					{       
//						if($aattach != null  && $aattach <> '')
//						{
//						$attachOut[] = $_SERVER["HTTP_HOST"] . "/tb/imageDctAdvice/" . $aattach;
//						}
//					}	
//					$actions[$k]['attach'] = $attachOut;
//				}
//			}	
//
//			//if($actions[$k]['steptypeid'] == xx)
//			if($actions[$k]['stepname'] == 'DA_bultra') //B超
//			{
//				$actions[$k]['leftovary'] = $actions[$k]['result1'];
//				$actions[$k]['rightovary'] = $actions[$k]['result2'];
//			}
//			else if($actions[$k]['stepname'] == 'DA_bloodtest') //验血
//			{
//				$actions[$k]['blood'] = $actions[$k]['result1'];
//			}	
//			unset($actions[$k]['result1']);
//			unset($actions[$k]['result2']);				
//    	}
//		
//    	$this->echoJson(array('result' => 0, 'actions' => $actions));	
//	} 	
	
	//====================================================================================
	//获取病人或医生的详细帐号信息。接口一样。输出内容不同。
	//http://121.40.78.46/tb/index.php?m=Home&c=App&a=getAccountDetail&uid=100000001
	public function getAccountDetail()
    {
		$uid  = I('request.uid');
                $hos=D("Hospital");
		if($uid > 100000000)
		{
	
	        $doctor_ds = D('Doctor');		
			$Account = $doctor_ds->where('id='.$uid)->find();
			$Account['truename'] = $Account['name'] ;
			unset($Account['name']);
			unset($Account['password']);
			unset($Account['captcha']);
			unset($Account['logincount']);
			//unset($Account['sex']);
                        if($Account['img']!=null){
                            $Account['img']='http://img.cndoc.ivf-bb.com/'.rtrim($Account['img'],',');
                        }
                        $r=$hos->where("id=".$Account['hospital_id'])->find();
                        $Account['hos_name']=$r['name'];
		}
		else
		{
			$user_ds = D('User');
			$Account = $user_ds->where('id='.$uid)->find();	
			$Account['logname'] = $Account['name'] ;
                        if($Account['image']!=null){
                            $Account['image']='http://img.user.ivf-bb.com/'.rtrim($Account['image'],',');
                        }
			unset($Account['name']);
			
			unset($Account['password']);
			unset($Account['groupchatids']);
			unset($Account['captcha']);
			unset($Account['logincount']);
			
			//unset($Account['sex']);				
		}	
        $this->echoJson(array('result' => 0, 'Account' => $Account)); 										
    }	
	//====================================================================================
	//修改病人或医生的详细帐号信息。
	//http://121.40.78.46/tb/index.php?m=Home&c=App&a=ModifyAccountDetail&uid=100000001&其它参数	
	//医生参数: truename,birthday,sex,descrip(职位描述),title(职位)
	//病人参数: truename,birthday,sex
	//birthday:字符串形式，如:2010-10-11。
	//sex:0女，1男.
	//例: http://121.40.78.46/tb/index.php?m=Home&c=App&a=ModifyAccountDetail&uid=37&truename=李王&birthday=14444789878&sex=1
	public function ModifyAccountDetail()
	{
		$uid  = I('request.uid');
		if($uid > 100000000)
		{
	        $doctor_ds = D('Doctor');	
			$data['name'] = I('request.truename');          if($data['name'] == '') unset($data['name']);
			//$data['telephone'] = I('request.telephone');  if($data['telephone'] == '') unset($data['telephone']);
            $data['birthday'] = I('request.birthday');      if($data['birthday'] == '') unset($data['birthday']);
			$data['sex'] = I('request.sex');                if($data['sex'] == '') unset($data['sex']);
			
			$data['descrip'] = I('request.descrip');        if($data['descrip'] == '') unset($data['descrip']);
			$data['title'] = I('request.title');            if($data['title'] == '') unset($data['title']);
			//$data['dept'] = I('request.dept');            if($data['dept'] == '') unset($data['dept']);
			$Account = $doctor_ds->where('id='.$uid)->save($data);
		
		}
		else
		{
			$user_ds = D('User');
                        $data['name'] = I('request.name');       if($data['name'] == '') unset($data['name']);
//			$data['truename'] = I('request.truename');       if($data['truename'] == '') unset($data['truename']);
			//$data['telephone'] = I('request.telephone');   if($data['telephone'] == '') unset($data['telephone']);
//            $data['birthday'] = I('request.birthday');       if($data['birthday'] == '') unset($data['birthday']);
//			$data['sex'] = I('request.sex');	             if($data['sex'] == '') unset($data['sex']);
			$Account = $user_ds->where('id='.$uid)->save($data);	
			
		}	
        $this->echoJson(array('result' => 0, 'Account' => $Account)); 			
	}
	//====================================================================================
	//获取租车信息列表
	//http://121.40.78.46/tb/index.php?m=Home&c=App&a=GetCarRentalList&step=10&fromid=0
	//step: 取多少个
	//fromid:从哪个id起(上次的最后一个id)，返回从下一个id起
	public function GetCarRentalList()
	{
    	$id = intval(I('request.fromid'));
		$step = intval(I('request.step'));
		if($step==0)
		{
		    $step = 99999;
		}
		
	    $CarRental_ds = D('carrent'); 
        $CarRentalList = $CarRental_ds->where('id>'.$id)->limit($step)->select();

    	foreach ($CarRentalList as $k => $v)
		{
			unset($CarRentalList[$k]['introduce']);
            $attachx = explode(",",$CarRentalList[$k]['pics']);
			if( count($attachx) > 0) //不能用$attachx != null
			{
				$attachOut = array();
				foreach ($attachx as $aattach)
				{
				    if($aattach != null  && $aattach !='')
					{
					    $attachOut[] = 'http://img.other.ivf-bb.com/imageCarRental/' . $aattach;
					}
					break;//先只给一张。
				}	
				$CarRentalList[$k]['pics'] = $attachOut;	
			}
			//else
			{
			   // $CarRentalList[$k]['pics'] = "";
			}		
    	} 
		
    	$this->echoJson(array('result' => 0, 'CarRentalList' => $CarRentalList));		
    }	
	//====================================================================================
	/*
	获取一个租车店的详细信息。
	http://121.40.78.46/tb/index.php?m=Home&c=App&a=GetACarRentDetail&id=2
	>>id: 租车店id
	*/
	public function GetACarRentDetail()
	{
	    $id = intval(I('request.id'));		
	    $CarRental_ds = D('carrent'); 
		
		
		$CarRentDetail = $CarRental_ds->where('id='.$id)->find();
		$CarRental_ds->where('id='.$id)->setInc('visitcount', 1);
		 
		$attachx = explode(",",$CarRentDetail['pics']);
		if( count($attachx) > 0) //不能用$attachx != null
		{
			$attachOut = array();
			foreach ($attachx as $aattach){
				if($aattach != null  && $aattach !='')
				{
					$attachOut[] = "http://img.other.ivf-bb.com/imageCareCenter/" . $aattach;
				}
			}	
			$CarRentDetail['pics'] = $attachOut;	
		}
		//else
		{
		   // $CarRentDetail['pics'] = "";
		}	
		
		 $this->echoJson(array('result' => 0, 'CarRentDetail' => $CarRentDetail));	
    }	
   //====================================================================================	
   /*
   >>增加、删除或修改一条对租车店的评论。暂时只有文字，不具有打分功能。
   >>增加: http://121.40.78.46/tb/index.php?m=Home&c=App&a=OperCarRentMark&action=add&carrentid=3&uid=5&mark=很好
   >>删除: http://121.40.78.46/tb/index.php?m=Home&c=App&a=OperCarRentMark&action=del&carrentid=3&uid=5&markid=3
   >>修改: http://121.40.78.46/tb/index.php?m=Home&c=App&a=OperCarRentMark&action=mod&carrentid=3&uid=5&markid=3&mark=一般
   >>查询：http://121.40.78.46/tb/index.php?m=Home&c=App&a=OperCarRentMark&action=qry&carrentid=3&step=10&fromid=99999
   >>入参[必]: action: add=增加，del=删除，mod=修改
   >>入参[必]: carrentid:租车店id，   
   >>入参[必]: uid :评价人id   
   >>入参: mark: 评价的文字内容
   >>入参: markid: 评价id,修改时才需要。
   >>入参: step,查询时才要。每次查多少条记录。0为无限。
   >>入参: fromid,查询时才要。上次查询的最后一条。这里查询是按时间倒序查的，所以这个是上次查询中最小的id。
   
   */
	public function OperCarRentMark()
	{
		$action = I('request.action');
		$carrentid = intval(I('request.carrentid'));
		$uid = intval(I('request.uid'));
		
		$mark = I('request.mark');		
		$markid = intval(I('request.markid'));
		
    	$id = intval(I('request.fromid'));			
		$step = intval(I('request.step'));		
		
		$carrentmark_ds = D('carrentmark'); 
		$carrent_ds = D('carrent'); //计算point
		
		if($action=='' || $carrentid==0)
		{
			$this->echoJson(array('result' => 2, 'err' => 'action,carrentid 必须'));
			exit;				
		}
		
		if($action == 'add')
		{
			$data['carrentid'] = $carrentid;
			$data['uid'] = $uid;
			$data['mark'] = $mark;
			$data['time'] = time();	
			
			$ccmarkid = $carrentmark_ds->add($data);
			
			if (!$ccmarkid)		
			{
				$this->echoJson(array('result' => 9, 'reason' => '数据保存到数据库失败'));
			} else {
				$carrent_ds->where('id='.$carrentid)->setInc('commentcount', 1);
				$this->echoJson(array('result' => 0, 'ccmarkid' => intval($ccmarkid)));
			}				
		}
		else if($action == 'del')
		{
			$carrentmark_ds->where('id='. $markid)->delete(); 
			$carrent_ds->where('id='.$carrentid)->setDec('commentcount', 1);
			$this->echoJson(array('result' => 0, 'del' => 'OK'));
			exit;			
		}
		else if($action == 'mod')
		{
			$result1 = $carrentmark_ds->where('id='.$markid)->setField('mark', $mark);
			$this->echoJson(array('result' => 0, 'mod' => 'OK'));
			exit;				
		}
		else if($action == 'qry')
		{
			if($id==0 || $id==-1) {$id=99999;} 	
			if($step==0) {	 $step = 99999; }	
            //时间倒序查询			
			$marklist = $carrentmark_ds->where('id<'.$id . ' and carrentid=' . $carrentid)->limit($step)->select();
			$this->echoJson(array('result' => 0, 'marklist' => $marklist));
			exit;				
		}		
		else
		{
			$this->echoJson(array('result' => 1, 'reason' => 'action错'));
		}

	}		
   //=====================================	
	//获取月子中心信息列表
	//http://121.40.78.46/tb/index.php?m=Home&c=App&a=GetPNCareCenterList&step=5&fromid=3
	//step: 取多少个
	//fromid:从哪个id起(上次的最后一个id)，返回从下一个id起
	public function GetPNCareCenterList()
	{
	    $fromid = intval(I('request.fromid'));
		$step = intval(I('request.step'));
		if($step==0)
		{
		    $step = 99999;
		}		
	    $carecenter_ds = D('carecenter'); 
		$CareCenterList = $carecenter_ds->where('id>'.$fromid)->limit($step)->select();
		 
    	foreach ($CareCenterList as $k => $v)
		{
			unset($CareCenterList[$k]['introduce']);
            $attachx = explode(",",$CareCenterList[$k]['pics']);
			if( count($attachx) > 0) //不能用$attachx != null
			{
				$attachOut = array();
				foreach ($attachx as $aattach)
				{
				    if($aattach != null  && $aattach !='')
					{
					    $attachOut[] = "http://img.other.ivf-bb.com/imageCareCenter/" . $aattach;
					}
					break;//先只给一张。
				}	
				$CareCenterList[$k]['pics'] = $attachOut;	
			}
			//else
			{
			   // $CareCenterList[$k]['pics'] = "";
			}		
    	}   		 
		 
		$this->echoJson(array('result' => 0, 'CareCenterList' => $CareCenterList));	
    }	
   //------------------------------------	
   //获取一个月子中心详细信息。
   //http://121.40.78.46/tb/index.php?m=Home&c=App&a=GetAPNCareCenterDetail&id=2
	public function GetAPNCareCenterDetail()
	{
	    $id = intval(I('request.id'));
		
	    $carecenter_ds = D('carecenter'); 
		$CareCenterDetail = $carecenter_ds->where('id='.$id)->find();
		$carecenter_ds->where('id='.$id)->setInc('visitcount', 1);
		 
		$attachx = explode(",",  rtrim($CareCenterDetail['imgs'],','));
		if( count($attachx) > 0) //不能用$attachx != null
		{
			$attachOut = array();
			foreach ($attachx as $aattach){
				if($aattach != null  && $aattach !='')
				{
					$attachOut[] = "http://img.other.ivf-bb.com/imageCareCenter_xx/" . $aattach;
				}
			}	
			$CareCenterDetail['pics'] = $attachOut;	
		}
		else
		{
		    $CareCenterDetail['pics'] = "";
		}	
		
		 $this->echoJson(array('result' => 0, 'CareCenterDetail' => $CareCenterDetail));	
    }	
   //====================================================================================	
   /*
   >>增加或修改一个对月子中心的评论。暂时只有文字，不具有打分功能。
   >>增加: http://121.40.78.46/tb/index.php?m=Home&c=App&a=OperCareCenterMark&action=add&centerid=3&uid=5&mark=很好
   >>删除: http://121.40.78.46/tb/index.php?m=Home&c=App&a=OperCareCenterMark&action=del&centerid=3&uid=5&markid=3
   >>修改: http://121.40.78.46/tb/index.php?m=Home&c=App&a=OperCareCenterMark&action=mod&centerid=3&uid=5&markid=3&mark=一般
   >>查询: http://121.40.78.46/tb/index.php?m=Home&c=App&a=OperCareCenterMark&action=qry&centerid=3&step=10&fromid=99999   
   >>入参[必]: action: add=增加，del=删除，mod=修改
   >>入参[必]: centerid:月子中心id，   
   >>入参[add时必]: uid :评价人id   
   >>入参: mark: 评价的文字内容
   >>入参: markid: 评价id,修改时才需要。
   */
	public function OperCareCenterMark()
	{
		$action = I('request.action');
		$centerid = intval(I('request.centerid'));
		$uid = intval(I('request.uid'));
		
		$mark = I('request.mark');		
		$markid = intval(I('request.markid'));
		
    	$id = intval(I('request.fromid'));			
		$step = intval(I('request.step'));			
		
		$carecentermark_ds = D('carecentermark'); 
		$carecenter_ds = D('carecenter'); //计算point
		
		if($action=='' || $centerid==0  )
		{
			$this->echoJson(array('result' => 2, 'err' => 'action,centerid 必须'));
			exit;				
		}
		
		if($action == 'add')
		{
			$data['carecenterid'] = $centerid;
			$data['uid'] = $uid;
			$data['mark'] = $mark;
			$data['time'] = time();	
			
			$ccmarkid = $carecentermark_ds->add($data);
			$carecenter_ds->where('id='.$centerid)->setInc('commentcount', 1);
			
			if (!$ccmarkid)		
			{
				$this->echoJson(array('result' => 9, 'reason' => '数据保存到数据库失败'));
			} else {
				$this->echoJson(array('result' => 0, 'ccmarkid' => intval($ccmarkid)));
			}				
		}
		else if($action == 'del')
		{
			$carecentermark_ds->where('id='. $markid)->delete(); 
			$carecenter_ds->where('id='.$centerid)->setDec('commentcount', 1);
			$this->echoJson(array('result' => 0, 'del' => 'OK'));
			exit;			
		}
		else if($action == 'mod')
		{
			$result1 = $carecentermark_ds->where('id='.$markid)->setField('mark', $mark);
			$this->echoJson(array('result' => 0, 'mod' => 'OK'));
			exit;				
		}
		else if($action == 'qry')
		{
			if($id==0 || $id==-1) {$id=99999;} 	
			if($step==0) {	 $step = 99999; }	
            //时间倒序查询			
			$marklist = $carecentermark_ds->where('id<'.$id . ' and carecenterid=' . $centerid)->limit($step)->select();
			$this->echoJson(array('result' => 0, 'marklist' => $marklist));
			exit;				
		}				
		else
		{
			$this->echoJson(array('result' => 1, 'reason' => 'action错'));
		}

	}
   //====================================================================================	
   //获取一个商家的产品列表。租车，月子中心，其它商品  共用。
   //http://121.40.78.46/tb/index.php?m=Home&c=App&a=GetProductsBySellerCode&SellerCode=YZ001
   //SellerCode:商家代码（如YZ001,CR002）。因为商家表不统一，所以不要使用 商家id，
	public function GetProductsBySellerCode()
	{
	    $SellerCode = I('request.SellerCode');
		
	    $products_ds = D('products'); 
		$productslist = $products_ds->where("sellercode='".$SellerCode ."'")->select();
		
		 $this->echoJson(array('result' => 0, 'productslist' => $productslist));	
    }	
		
   //====================================================================================	
   //产品加入购物车，或修改购物车中数量，为0时删除。
   //http://121.40.78.46/tb/index.php?m=Home&c=App&a=AddModProductsForCart&uid=11&productid=34&action=add&quantity=4
   //action: add加入购物车，mod修改数量(0时删除)
   //uid:用户id，
   //productid : 商品id(1,2,3..), 不是商品code(YZ001-001)
   //quantity: add时是本次多加了几个。mod修改时是修改后最终的数量,如果要删除就mod--0. 
//	public function AddModProductsForCart()
//	{
//	    $action = I('request.action');
//		$uid = I('request.uid');
//		$productid = I('request.productid');
//		$quantity = I('request.quantity');
//		
//	    $shopping_cart_ds = D('shopping_cart'); 
//		if($action == 'add')
//		{
//			$rec = $shopping_cart_ds->where("uid=".$uid ." and productid=" . $productid)->find();
//			if($rec == null) //不存在
//			{
//				$data['uid'] = $uid;
//				$data['productid'] = $productid;
//				//$data['productcode'] =xx;	
//				//$data['unitprice'] =xx;	
//				$data['quantity'] = $quantity;
//				
//				$id = $shopping_cart_ds->add($data);	
//			}
//			else //增加。
//			{
//			    $shopping_cart_ds->where("uid=".$uid ." and productid=" . $productid)->setInc('quantity', $quantity);
//			}
//			//$this->echoJson(array('result' => 0, 'add' => 'OK'));
//			//exit;
//		
//		}
//		else if($quantity <= 0) //del
//		{
//		    $shopping_cart_ds->where("uid=".$uid ." and productid=" . $productid)->delete();
//			//$this->echoJson(array('result' => 0, 'quantity=0' => 'OK'));
//			//exit;
//		}
//		else //mod
//		{
//		    $shopping_cart_ds->where("uid=".$uid ." and productid=" . $productid)->setField('quantity', $quantity);
//			//$this->echoJson(array('result' => 0, 'modCommon' => 'OK'));
//			//exit;
//		}
//		
//		$this->echoJson(array('result' => 0, 'Oper' => 'OK'));	
//    }			
		
   //====================================================================================	
   //购物车 --- 》 去结算 --- 》 提交订单 --》 确认支付 --> 确认支付成功。
   //查询某人的购物车内容。
   //http://121.40.78.46/tb/index.php?m=Home&c=App&a=QueryShoppingCart&uid=11
   //uid:用户id
//	public function QueryShoppingCart()
//	{
//	    $uid = I('request.uid');
//		
//		$shopping_cart_ds = D('shopping_cart'); 
//		$products_ds = D('products');  
//		
//		$Products = $shopping_cart_ds->where("uid=".$uid )->select();
//		foreach ($Products as $k => $v)
//		{
//			$product = $products_ds->where('id='.$v['productid'])->find();
//			$Products[$k]['productcode'] = $product['productcode'];
//			$Products[$k]['productname'] = $product['productname'];
//			$Products[$k]['unitprice'] = $product['unitprice'];
//			$Products[$k]['unit'] = $product['unit'];
//			unset($Products[$k]['uid']); 
//			unset($Products[$k]['id']); 
//
//		}			
//		
//		$this->echoJson(array('result' => 0, 'Products' => $Products));			
//    }	
		
  //====================================================================================	
   //订单入库。在购物车界面选择商品后，点击“去结算”，APP弹出汇总信息，然后用户"提交订单"。
   //http://121.40.78.46/tb/index.php?m=Home&c=App&a=PlaceOrder&uid=11&productids=1;2;3
   //uid:用户id
   //productids: 以分号分隔的 商品id
   
   //有可能：在前面获取价格后，到这里 中间价格修改。概率太小，先不管了。
   //还有可能商品下架了。严格地说，这里应该检查一下。
//	public function PlaceOrder()
//	{
//	    $uid = I('request.uid');
//		$productids = I('request.productids');
//		
//		$shopping_cart_ds = D('shopping_cart'); 
//		$products_ds = D('products');  
//		$buyorder_ds = D('buyorder'); //（购买）订单入库。
//		
//		//$price = 0.01;		
//		$productidarr = explode(";",$productids);
//		$time = time();
//		if(count($productidarr) > 0)
//		{
//			foreach ($productidarr as $productid)
//			{       
//				if($productid != null && $productid <> '')
//				{
//					$data['orderid'] = $time; //多个产品共用同一个 orderid，这个同时也就是时间。
//					$data['uid'] = $uid;
//					$data['buytime'] =  date("Ymd H:i:s",$time);
//					//$data['buytime2'] = date("Ymd H:i:s",$data['buytime']);
//					$data['productid'] = $productid;
//					
//					$rec1 = $products_ds->where("id=".$productid)->find();
//					$data['unitprice'] = $rec1['unitprice'];
//					
//					$rec2 = $shopping_cart_ds->where("uid=" .$uid . " and productid=" .$productid)->find();
//					$data['quantity'] = $rec2['quantity'];					
//					
//					$data['totalprice'] = $data['unitprice'] * $data['quantity'] ;	
//					
//				    $id = $buyorder_ds->add($data);
//				}
//			} //for
//
//		}		
//		
//		$this->echoJson(array('result' => 0, 'orderid' => $time));			
//    }			
		
		
  //====================================================================================	
   //用户"提交订单"，然后点击“确认支付”。 或 用户"充值"
   //“确认支付”: http://121.40.78.46/tb/index.php?m=Home&c=App&a=PayOrder&uid=11&orderid=1449301178
   //"充值": http://121.40.78.46/tb/index.php?m=Home&c=App&a=PayOrder&uid=11&addmoney=100
   //uid:用户id
   //orderid: 订单id
   //addmoney: 充值多少钱。
   //APP使用浏览器控件或手机浏览器，访问服务器返回的URL。
//	public function PayOrder()
//	{
//	     $uid = I('request.uid');
//		 $orderid = I('request.orderid');
//		 $addmoney = I('request.addmoney');
//		 //$addmoney = 0.01;
//		 //$url = "http://121.40.78.46/tb/mas_demo/orderPay/indexqb.php?uid=11&orderid=1";1448673282
//		 //$url = "http://ivf-bb.com/tb/mas_demo/orderPay/indexqb.php?uid=11&orderid=1";
//		 //$url = "http://" .$_SERVER["HTTP_HOST"] . "/tb/mas_demo/orderPay/indexqb.php?uid=" . $uid . "&orderid=" . $orderid;//IP，
//		 if($addmoney == '' || $addmoney == null)
//		 {
//		     $url = "http://ivf-bb.com/tb/mas_demo/orderPay/indexqb.php?uid=" . $uid . "&orderid=" . $orderid;//盛付通接口现在按域名 ivf-bb.com 来限制安全性的。
//		 }
//		 else
//		 {
//		     $url = "http://ivf-bb.com/tb/mas_demo/orderPay/indexqb.php?uid=" . $uid . "&addmoney=" . 0.01;
//		 }
////http://ivf-bb.com/tb/mas_demo/orderPay/indexqb.php?uid=37&orderid=1449301178
//		 
//		 $this->echoJson(array('result' => 0, 'url' => $url));	
//		 
//		 //http://blog.csdn.net/jinxingfeng_cn/article/details/24960981
//		 //$_SERVER["HTTP_HOST"]   当前请求头中 Host: 项的内容，如果存在的话。
//		 //$_SERVER["SERVER_NAME"]  --主机名?
//		 //$_SERVER["SERVER_ADDR"]  --- IP 地址
//
//    }	
	
   //====================================================================================	
   //确认支付成功。
   //http://121.40.78.46/tb/index.php?m=Home&c=App&a=PayOrderSucc&uid=11&orderid=1
   //uid:用户id
   //orderid: 订单id
   //APP端要求确认成功，不需要处理函数结果。如果是失败就不必调用了
//	public function PayOrderSucc()
//	{
//	     $uid = I('request.uid');
//		 $orderid = I('request.orderid');
//		 //....设置状态：//未完成qqqq?????
//
//		 $this->echoJson(array('result' => 0, 'oper' => 'OK'));	
//    }			
		
   //====================================================================================	
   //查询资金流：充值和咨询扣款。不包括购物。
   //http://121.40.78.46/tb/index.php?m=Home&c=App&a=QueryMoneyFlow&uid=11&fromtime=2015-11-01&totime=2015-11-30
   //uid:用户id	
   //fromtime,totime起止时间，格式为 2015-11-01 
   //如果不带 fromtime,totime 参数，则查询所有。   
//	public function QueryMoneyFlow()
//	{
//	     $uid = I('request.uid');
//		 $fromtime = I('request.fromtime');
//		 if($fromtime != "")
//		 {
//		   $fromtime = I('request.fromtime') . "00:00:00";
//		   $totime   = I('request.totime') . "23:59:59";
//		 }
//		 
//		 $money_flow_ds = D('money_flow'); 
//		if($fromtime != "")
//        {		
//		    $moneyflow = $money_flow_ds->where("uid=".$uid . " and time>='" .$fromtime . "' and time<='" .$totime . "'")->select();
//		}
//		else
//		{
//		    $moneyflow = $money_flow_ds->where("uid=".$uid )->select();
//		}
//    	
//    	foreach ($moneyflow as $k => $v){
//    		//unset($moneyflow[$k]['uid']);  		
//    	}
//
//		$this->echoJson(array('result' => 0, 'moneyflow' => $moneyflow)); 								
//	
//	}	
   //====================================================================================	
   //新增/修改病历信息, (删除调用 SetUserinfoDiagnosisStatus )
   //http://121.40.78.46/tb/index.php?m=Home&c=App&a=AddModUserinfoDiagnosis&uid=11&其它参数见<数据库表设计.xlsx>表tb_userinfo_diagnosis
   //uid:用户id
   //其它参数:见<数据库表设计.xlsx>表tb_userinfo_diagnosis   
   //这么多参数能带么？   
	public function AddModUserinfoDiagnosis()
	{
	    $uid = I('request.uid');
		
//$data['id'] = I('request.id');
            
$data['moddate'] = I('request.filldate');

//以下参数需要APP传入
//$data['userid'] = I('request.userid');
$data['truename'] = I('request.truename');
$data['birthday'] = I('request.birthday');
$data['height'] = I('request.height');
$data['weight'] = I('request.weight');
$data['marital'] = I('request.marital');
$data['marital_year'] = I('request.marital_year');
$data['spouse_name'] = I('request.spouse_name');
$data['spousebirthday'] = I('request.spousebirthday');
$data['last_mens_day'] = I('request.last_mens_day');
$data['ruanpao'] = I('request.ruanpao');
$data['huangti'] = I('request.huangti');
$data['ci2chun'] = I('request.ci2chun');
$data['yuntong'] = I('request.yuntong');
$data['gaotong'] = I('request.gaotong');
$data['cuiru'] = I('request.cuiru');
$data['amh'] = I('request.amh');
$data['menstrual_days'] = I('request.menstrual_days');
$data['menstrual_cycle'] = I('request.menstrual_cycle');
$data['menstrual_amount'] = I('request.menstrual_amount');
$data['leftruanpaocnt'] = I('request.leftruanpaocnt');
$data['rightruanpaocnt'] = I('request.rightruanpaocnt');
$data['endome_thick'] = I('request.endome_thick');
$data['hysteromyoma'] = I('request.hysteromyoma');
$data['pregnant_count'] = I('request.pregnant_count');
$data['abortion_count'] = I('request.abortion_count');
$data['stillbirth'] = I('request.stillbirth');
$data['gongwaiyun'] = I('request.gongwaiyun');
$data['sperm_date'] = I('request.sperm_date');
$data['sperm_result'] = I('request.sperm_result');
$data['a_sperm_date'] = I('request.a_sperm_date');
$data['a_sperm_result'] = I('request.a_sperm_result');
$data['sperm_through_date'] = I('request.sperm_through_date');
$data['sperm_through_result'] = I('request.sperm_through_result');
$data['shiguanmudi'] = I('request.shiguanmudi');
//$data['cupaicnt'] = I('request.cupaicnt');
//$data['zhuyuncnt'] = I('request.zhuyuncnt');

	    //$data['status'] = I('request.status');
            foreach ($data as $k=>$v){
                if($v==''){
                    unset($data[$k]);
                }
            }
		$userinfo_diagnosis_ds = D('userinfo_diagnosis'); 
		//先查一下，如果有就修改，如果没有就插入。 
		$userdiagnosis = $userinfo_diagnosis_ds->where('userid='.$uid)->find();
		if ($userdiagnosis == null) //新增
		{
			$data['userid'] = $uid ;
			$data['status'] = "W"; //未推
			$re = $userinfo_diagnosis_ds->add($data);
		}
		else //修改
		{
			$re = $userinfo_diagnosis_ds->where('userid='.$uid)->save($data);
		}			 
		 //$DiagnosisInfo   = $userinfo_diagnosis_ds->where('userid='.$uid)->find();					

		$this->echoJson(array('result' => 0, 'AddMod' => "OK"));	
    }
    //删除病例图像
    ////type 1为验血单 2为左卵巢 3为右卵巢 4精子图
    public function del_bingli_img($type){
                    $uid=I("request.uid");
                    $imgname=I("request.img_name");
                    $UInfoDiag_ds = D('userinfo_diagnosis'); 	
                    $rec = $UInfoDiag_ds->where('userid='.$uid)->find();
                    if(!$rec){
                        $this->echoJson(array('result' => 1, 'info' => "没有此数据"));exit;
                    }
                    
                    
                    if($type==1){
                        unlink("./image_binli/".$imgname);
                        $imageone=str_replace($imgname.',',"",$rec['imgone']);
                        if($imageone==$rec['imgone']){
                            $this->echoJson(array('result' => 1, 'info' => "没有此图片"));exit;
                        }
                        $data['imgone']=$imageone;
                    }else if($type==2){
                        unlink("./image_binli/".$imgname);
                        $leftimg=str_replace($imgname.',',"",$rec['leftimg']);
                        if($leftimg==$rec['leftimg']){
                            $this->echoJson(array('result' => 1, 'info' => "没有此图片"));exit;
                        }
                        $data['leftimg']=$leftimg;
                    }else if($type==3){
                        unlink("./image_binli/".$imgname);
                        $rightimg=str_replace($imgname.',',"",$rec['rightimg']);
                        if($rightimg==$rec['rightimg']){
                            $this->echoJson(array('result' => 1, 'info' => "没有此图片"));exit;
                        }
                        $data['rightimg']=$rightimg;
                    }else if($type==4){
                        unlink("./image_binli/".$imgname);
                        $jingziimg=str_replace($imgname.',',"",$rec['jingziimg']);
                        if($jingziimg==$rec['jingziimg']){
                            $this->echoJson(array('result' => 1, 'info' => "没有此图片"));exit;
                        }
                        $data['jingziimg']=$jingziimg;
                    }
                    
                    $r = $UInfoDiag_ds->where('userid='.$uid)->save($data);
                    if(!$r){
                        $this->echoJson(array('result' => 1, 'info' => "删除失败"));exit;
                    }
                    $this->echoJson(array('result' => 0, 'info' => "删除成功"));exit;
    }
    //上传病例图像
    //type 1为验血单 2为左卵巢 3为右卵巢 4精子图
        public function upload_binli_img(){
  
		$type = intval(I('request.type'));
		$uid = intval(I('request.uid'));
//		$destination_folder="./image_binli/";  
				
        	$setting=C('UPLOAD_SITEIMG_QINIU');
                $setting['driverConfig']['domain']='img.other.ivf-bb.com';
                $setting['driverConfig']['bucket'] = 'imageother';
//		$setting['saveName'] = array ('uniqid', 'image_binli_');
                $setting['subName'] = 'image_binli/'.date('Y-m-d',time());
                    $Upload = new \Think\Upload($setting);
                    $info = $Upload->upload($_FILES);
                    $t=  date('Y-m-d',time());
                    $name='';
                    foreach ($info as $v){
                        $name.=$t.'/'.$v['savename'].',';
                    }
                    //添加数据库
                    $data['uid']=intval($uid);
                    if($type==1){
                        $data['imgone']=$name;
                        
                    }else if($type==2){
                        $data['leftimg']=$name;
                    }else if($type==3){
                        $data['rightimg']=$name;
                    }else if($type==4){
                        $data['jingziimg']=$name;
                    }
                    $UInfoDiag_ds = D('userinfo_diagnosis'); 	
                    $rec = $UInfoDiag_ds->where('userid='.$uid)->find();
                    if(!$rec){
                        $UInfoDiag_ds->add($data);
                        $this->echoJson(array('result' => 0, 'info' => "添加成功"));
                    }
                    if($type==1){
                        $data['imgone'].=$rec['imgone'];
                    }else if($type==2){
                        $data['leftimg'].=$rec['leftimg'];
                    }else if($type==3){
                        $data['rightimg'].=$rec['rightimg'];
                    }else if($type==4){
                        $data['jingziimg'].= $rec['jingziimg'];
                    }
                    $r = $UInfoDiag_ds->where('userid='.$uid)->save($data);
                    if(!$r){
                        $this->echoJson(array('result' => 1, 'info' => "修改失败"));
                    }else{
                        $this->echoJson(array('result' => 0, 'info' => "修改成功"));
                    }
                    
    }
    
    
  //====================================================================================	
   //对 用户病历信息 设置  推送/不推送/删除  标志  
   //http://121.40.78.46/tb/index.php?m=Home&c=App&a=SetUserinfoDiagnosisStatus&uid=11&status=W&doctorid=-1
   //uid:用户id
   //doctorid:推送时才需要。被推送的医生id，-1=所有医生。其它比如地区，再讨论???。
   //status: W未推(撤回)，T已推，A有医生接诊，D病人接受了一个医生。全大写! ,其中AD不需要APP设置。
   //APP:如果当前是 T,A，则不应该再  T， 如果推了，服务器直接忽略。
   //APP:如果当前是 W,D，则不应该再  W,  如果推了，服务器直接忽略。
   //用户在取消推送时，如果有医生已经接诊了应该提示最好不要撤回，除非确实不想问诊了，如果只是想修改一下不需要撤回。
	public function SetUserinfoDiagnosisStatus()
	{
		$uid = I('request.uid');
		$status = I('request.status');
        $doctorid = I('request.doctorid');		
		
        $data['status'] = $status;			
		
		$UInfoDiag_ds = D('userinfo_diagnosis'); 
		$UInfoDiagTrade_ds = D('userinfo_diagnosis_trade');	
        $user_ds = D('User');		
		 
		 $rec = $UInfoDiag_ds->where('userid='.$uid)->find();
                 if(!$rec){
                     $this->echoJson(array('result' => 1, 'SetStatus' => "用户还未添加病例"));exit;
                 }
         if($status=='T')
		 {
			 if($rec['status']=='T' || $rec['status']=='A' )
			 {//啥也不做
                             $this->echoJson(array('result' => 2, 'SetStatus' => "您已推送过,请勿重复操作"));exit;
		     }		 
			else //真要推。
			 {
				$man = $user_ds->where('id='.$uid)->find();
				//$MP = 100;
				//if($man['money_available'] < 100) //这个100是个坑啊。????
                                if($man['money_available'] <0)
				{
				    $this->echoJson(array('result' => 1, 'SetStatus' => "钱不够请充值"));
					exit;
				}
				else
				{
				    $user_ds->where('id='.$uid)->setInc('money_available',-0);//-100
					$user_ds->where('id='.$uid)->setField('money_freeze',0);  //=100
				}
				
				$dataT['bingliid'] = $rec['id'];
				$dataT['userid'] = $rec['userid'];
				$dataT['ts_doctor'] = $doctorid;
				$dataT['ts_time'] = date('Y-m-d H:i:s',time());
				//$dataT['acpt_doctor'] = $xx;
				//$dataT['acpt_time'] = $xx;
				//$dataT['deal_doctor'] = $xx;	
				//$dataT['deal_time'] = $xx;
				$dataT['status'] = 'T';				
				$UInfoDiagTrade_ds->add($dataT);
				$re = $UInfoDiag_ds->where('userid='.$uid)->save($data);
                                if($doctorid=="-1"){
                                    $this->Jpush("有病人的病例,请查看",array('alias'=>array('doctor')),"doctor"); 
                                }else{
                                    $this->Jpush("有病人的病例,请查看",array('tag'=>array($doctorid)),"doctor");
                                }
			 }	
		 }	
         else if($status=='W')	//撤回
		 {
			 if($rec['status']=='W' || $rec['status']=='D')
			 {//啥也不做
		     }		
			 else //尚未成交，真要撤，直接删除。
			 {
				 $user_ds->where('id='.$uid)->setInc('money_available',0);//+100
				 $user_ds->where('id='.$uid)->setField('money_freeze',0);	//-100	 	 
				 $UInfoDiagTrade_ds->where("uid=" . $uid . " and status!='H'")->delete();
				 $re = $UInfoDiag_ds->where('userid='.$uid)->save($data);
			 }	
		 }
         else
		 {
			 $this->echoJson(array('result' => 2, 'SetStatus' => "参数错误"));
			 exit;
		 }			          	 
         
		 $this->echoJson(array('result' => 0, 'SetStatus' => "OK"));	
    }
    //====================================================================================	
   //获取用户病历信息. 医生端病人端共用。
   //http://121.40.78.46/tb/index.php?m=Home&c=App&a=GetUserinfoDiagnosis&uid=11
   //uid:用户id
	public function GetUserinfoDiagnosis()
	{
	     $uid = I('request.uid');
		 $userinfo_diagnosis_ds = D('userinfo_diagnosis'); 
		 $userinfo_diagnosis_cupai_ds = D('userinfo_diagnosis_cupai'); 
		 $userinfo_diagnosis_zhuyun_ds = D('userinfo_diagnosis_zhuyun'); 
		 
		 $DiagnosisInfo   = $userinfo_diagnosis_ds->where('userid='.$uid)->find();	
                 if(!$DiagnosisInfo){
                    $this->echoJson(array('result' => 1, 'info' => '没有此病例'));
			exit;	
                 }
                 if($DiagnosisInfo['imgone']!=null){
                    $arr=explode(",",rtrim($DiagnosisInfo['imgone'],','));
                    foreach($arr as &$v){
                        $v="http://img.other.ivf-bb.com/image_binli/".$v;
                    }
                    $DiagnosisInfo['imgone']=$arr;
                 }else{
                     $DiagnosisInfo['imgone']=array();
                 }
                 if($DiagnosisInfo['leftimg']!=null){
                    $arr=explode(",",rtrim($DiagnosisInfo['leftimg'],','));
                    foreach($arr as &$v){
                        $v="http://img.other.ivf-bb.com/image_binli/".$v;
                    }
                    $DiagnosisInfo['leftimg']=$arr;
                 }else{
                     $DiagnosisInfo['leftimg']=array();
                 }
                 if($DiagnosisInfo['rightimg']!=null){
                    $arr=explode(",",rtrim($DiagnosisInfo['rightimg'],','));
                    foreach($arr as &$v){
                        $v="http://img.other.ivf-bb.com/image_binli/".$v;
                    }
                    $DiagnosisInfo['rightimg']=$arr;
                 }else{
                     $DiagnosisInfo['rightimg']=array();
                 }
                 if($DiagnosisInfo['jingziimg']!=null){
                    $arr=explode(",",rtrim($DiagnosisInfo['jingziimg'],','));
                    foreach($arr as &$v){
                        $v="http://img.other.ivf-bb.com/image_binli/".$v;
                    }
                    $DiagnosisInfo['jingziimg']=$arr;
                 }else{
                     $DiagnosisInfo['jingziimg']=array();
                     
                 }
		 $cupai  = $userinfo_diagnosis_cupai_ds->where('bingliid='.$DiagnosisInfo['id'])->select();
		 $zhuyun = $userinfo_diagnosis_zhuyun_ds->where('bingliid='.$DiagnosisInfo['id'])->select();
                 $DiagnosisInfo['cupai']=$cupai;
                 $DiagnosisInfo['zhuyun']=$zhuyun;
		
		//unset($DiagnosisInfo['spouse_age']);
		//unset($DiagnosisInfo['artificial_abortion']);
        $this->echoJson(array('result' => 0, 'DiagnosisInfo' => $DiagnosisInfo));	
    }	
	//====================================================================================	
    /*  
   >>增加、删除或修改病历信息中的--促排信息。
   >>增加: http://121.40.78.46/tb/index.php?m=Home&c=App&a=OperUserinfoDiagnosis_cupai&action=add&bingliid=3&uid=5&其它参数
   >>删除: http://121.40.78.46/tb/index.php?m=Home&c=App&a=OperUserinfoDiagnosis_cupai&action=del&bingliid=3&uid=5&cupaiid=3
   >>修改: http://121.40.78.46/tb/index.php?m=Home&c=App&a=OperUserinfoDiagnosis_cupai&action=mod&bingliid=3&uid=5&cupaiid=3&其它参数
   >>入参[必]: action: add=增加，del=删除，mod=修改
   >>入参[必]: bingliid:病历id，   
   >>入参[必]: uid:用户id 
   >>入参: cupaiid: 促排id,删除/修改时才需要。 
   >>其它参数:见<数据库表设计.xlsx>表tb_userinfo_diagnosis_cuipai    
   */
	public function OperUserinfoDiagnosis_cupai()
	{
		$action = I('request.action');
		$bingliid = intval(I('request.bingliid'));
		$uid = intval(I('request.uid'));
		$cupaiid = intval(I('request.cupaiid'));
		
		$time = I('request.time');	
		$addr = I('request.addr');			
		$drug = I('request.drug');	
		$jiliang = I('request.jiliang');	

		
		$userinfo_diagnosis_cupai_ds = D('userinfo_diagnosis_cupai'); 
		$userinfo_diagnosis_ds = D('userinfo_diagnosis'); 
		
		if($action=='' || $bingliid==0 || $uid==0 )
		{
			$this->echoJson(array('result' => 2, 'err' => 'action,bingliid,uid必须'));
			exit;				
		}
		
		if($action == 'add')
		{
			$data['bingliid'] = $bingliid;
			$data['time'] = $time;
			$data['addr'] = $addr;			
			$data['drug'] = $drug;	
			$data['jiliang'] = $jiliang;	
			
			$cupaiidx = $userinfo_diagnosis_cupai_ds->add($data);			
			
			if (!$cupaiidx)		
			{
				$this->echoJson(array('result' => 9, 'reason' => '数据保存到数据库失败'));
			} else {
				$userinfo_diagnosis_ds->where('id='.$bingliid)->setInc('cupaicnt', 1);
				$this->echoJson(array('result' => 0, 'cupaiid' => intval($cupaiidx)));
			}				
		}
		else if($action == 'del')
		{
			$userinfo_diagnosis_cupai_ds->where('id='. $cupaiid)->delete(); 
			$userinfo_diagnosis_ds->where('id='.$bingliid)->setDec('cupaicnt', 1);
			$this->echoJson(array('result' => 0, 'del' => 'OK'));
			exit;			
		}
		else if($action == 'mod')
		{
			$result1 = $userinfo_diagnosis_cupai_ds->where('id='.$cupaiid)->save($data);
			$this->echoJson(array('result' => 0, 'mod' => 'OK'));
			exit;				
		}
		else
		{
			$this->echoJson(array('result' => 1, 'reason' => 'action错'));
		}	
	}		
   //====================================================================================	
    /*  
   >>增加、删除或修改病历信息中的--助孕信息。
   >>增加: http://121.40.78.46/tb/index.php?m=Home&c=App&a=OperUserinfoDiagnosis_zhuyun&action=add&bingliid=3&uid=5&其它参数
   >>删除: http://121.40.78.46/tb/index.php?m=Home&c=App&a=OperUserinfoDiagnosis_zhuyun&action=del&bingliid=3&uid=5&zhuyunid=3
   >>修改: http://121.40.78.46/tb/index.php?m=Home&c=App&a=OperUserinfoDiagnosis_zhuyun&action=mod&bingliid=3&uid=5&zhuyunid=3&其它参数
   >>入参[必]: action: add=增加，del=删除，mod=修改
   >>入参[必]: bingliid:病历id，   
   >>入参[必]: uid:用户id 
   >>入参: zhuyunid: 助孕id,删除/修改时才需要。 
   >>其它参数:见<数据库表设计.xlsx>表tb_userinfo_diagnosis_zhuyun    
   */ 
	public function OperUserinfoDiagnosis_zhuyun()
	{
		$action = I('request.action');
		$uid = intval(I('request.uid'));
		$bingliid = intval(I('request.bingliid'));		
		$zhuyunid = intval(I('request.zhuyunid'));
		
		$time = I('request.time');	
		$addr = I('request.addr');			
		
		$get_eggcnt = I('request.get_eggcnt');	
		$fert_eggcnt = I('request.fert_eggcnt');
                $peitai = I('request.peitai');
		$embryo_cnt = I('request.embryo_cnt');
			
		$userinfo_diagnosis_zhuyun_ds = D('userinfo_diagnosis_zhuyun'); 
		$userinfo_diagnosis_ds = D('userinfo_diagnosis'); 
		
		if($action=='' || $bingliid==0 || $uid==0 )
		{
			$this->echoJson(array('result' => 2, 'err' => 'action,bingliid,uid必须'));
			exit;				
		}
		
		if($action == 'add')
		{
			$data['bingliid'] = $bingliid;
			$data['time'] = $time;
			$data['addr'] = $addr;
			
			$data['get_eggcnt'] = $get_eggcnt;	
			$data['fert_eggcnt'] = $fert_eggcnt;
                        $data['peitai']=$peitai;
			$data['embryo_cnt'] = $embryo_cnt;
			
			$zhuyunidx = $userinfo_diagnosis_zhuyun_ds->add($data);			
			
			if (!$zhuyunidx)		
			{
				$this->echoJson(array('result' => 9, 'reason' => '数据保存到数据库失败'));
			} else {
				$userinfo_diagnosis_ds->where('id='.$bingliid)->setInc('zhuyuncnt', 1);
				$this->echoJson(array('result' => 0, 'zhuyunid' => intval($zhuyunidx)));
			}				
		}
		else if($action == 'del')
		{
			$userinfo_diagnosis_zhuyun_ds->where('id='. $zhuyunid)->delete(); 
			$userinfo_diagnosis_ds->where('id='.$bingliid)->setDec('zhuyuncnt', 1);
			$this->echoJson(array('result' => 0, 'del' => 'OK'));
			exit;			
		}
		else if($action == 'mod')
		{
			$result1 = $userinfo_diagnosis_zhuyun_ds->where('id='.$zhuyunid)->save($data);
			$this->echoJson(array('result' => 0, 'mod' => 'OK'));
			exit;				
		}
		else
		{
			$this->echoJson(array('result' => 1, 'reason' => 'action错'));
		}		
	}
 	//====================================================================================
	//医生端获取求诊信息的简要列表。（详细信息调用 获取）
	//http://121.40.78.46/tb/index.php?m=Home&c=App&a=Dct_GetUserinfoDiagnosisList&doctorid=100000003&fromid=-1&step=10
	//doctorid: 医生id
	//step: 取多少个
	//fromid:从哪个id起(上次的最后一个id)，返回从下一个id起
	//APP友好性：建议根据 ts_doctor，来特别标识，这个是病人指定推送的。
	//APP应根据 acpt_doctor 里是否包含本医生的id来特别标识-我已接诊此人。
	public function Dct_GetUserinfoDiagnosisList()
	{	
	    $fromid = intval(I('request.fromid'));
		$doctorid = intval(I('request.doctorid'));
		$step = intval(I('request.step'));		
		if($step==0)
		{
		    $step = 99999;
		}
		
	    $UInfoDiag_ds = D('userinfo_diagnosis');
		$UInfoDiagTrade_ds = D('userinfo_diagnosis_trade');
		$user_ds = D('User');
		
		//参考 http://zhidao.baidu.com/question/1819677454681550988.html?fr=iks&word=thinkphp+where+%B6%E0%B8%F6%CC%F5%BC%FE&ie=gbk
		//http://zhidao.baidu.com/question/1755675870329152028.html?fr=iks&word=thinkphp+where+%B6%E0%B8%F6%CC%F5%BC%FE&ie=gbk	
		//条件：id> $fromid && deal_doctor='' && status !='H' && (ts_doctor=$doctorid  || (ts_doctor=-1 && len(acpt_doctor)<21)) 
//		$cnd1['ts_doctor'] = -1;//加个条件：接诊医生未满三个
//		$cnd1['ts_doctor']  = $doctorid;
                 //$where['ts_doctor'] = array('in', "-1,$doctorid");
		//$cnd1['_logic'] = 'OR';
		//$where['id'] = array('gt',$fromid); 
		//$where['deal_doctor'] = '';  //病人还没有接受任何一个医生 
                //$where['status'] = array('neq','H'); 
		//$where['_complex'] = $cnd1;
		$where="id> $fromid and deal_doctor=0 and status !='H' and (ts_doctor=$doctorid  or (ts_doctor=-1 and LENGTH(acpt_doctor)<21))";
        $UInfoDiagList = $UInfoDiagTrade_ds->where($where)->limit($step)->select();
        if(count($UInfoDiagList)==0){
            $this->echoJson(array('result' => 0, 'UInfoDiagList' => $UInfoDiagList));exit;
        }
    	foreach ($UInfoDiagList as $k => $v)
		{
			//unset($UInfoDiagList[$k]['ts_doctor']);//这个可能APP也要，如果是指定医生的，医生可以更关注
			unset($UInfoDiagList[$k]['ts_time']);
			//unset($UInfoDiagList[$k]['acpt_doctor']);//这个推到APP，以判断这个记录我(医生)是否已接诊。
			unset($UInfoDiagList[$k]['acpt_time']);
			unset($UInfoDiagList[$k]['deal_doctor']);//反正是空的。
			unset($UInfoDiagList[$k]['deal_time']);
			unset($UInfoDiagList[$k]['status']);		
		
			$UInfoDiagList[$k]['tsid'] = $UInfoDiagList[$k]['id'];//推送id，改个名字，APP方便
			unset($UInfoDiagList[$k]['id']);
			
			$UInfoDiag = $UInfoDiag_ds->where('id=' . $UInfoDiagList[$k]['bingliid'])->find();
			$UInfoDiagList[$k]['truename'] = $UInfoDiag['truename'];
			$UInfoDiagList[$k]['birthday'] = $UInfoDiag['birthday'];
			//头像:
			$user = $user_ds->where("id=". $UInfoDiagList[$k]['userid'])->find();
			$UInfoDiagList[$k]['logname'] = $user['name'];
                        if($UInfoDiagList[$k]['headimage']!=null){
                            $UInfoDiagList[$k]['headimage'] = "http://img.user.ivf-bb.com/" .$user['image'];
                        }else{
                            $UInfoDiagList[$k]['headimage']='';
                        }
			//还需要什么信息再添加...???
    	} 
		
    	$this->echoJson(array('result' => 0, 'UInfoDiagList' => $UInfoDiagList));
	}	
	//====================================================================================
	//医生接诊，调用这个。
	//http://121.40.78.46/tb/index.php?m=Home&c=App&a=Dct_Admission&doctorid=100000003&tsid=11
	//doctorid: 医生id
	//tsid ：推送id (来自表 userinfo_diagnosis_trade)
	//APP: 应该在 heartbeat_user() 的结果中增加消息'6'=getA_Dct_Admission 的处理。
	public function Dct_Admission()
	{	
	    $tsid = intval(I('request.tsid'));
		$doctorid = intval(I('request.doctorid'));
		
	    $UInfoDiag_ds = D('userinfo_diagnosis');
		$UInfoDiagTrade_ds = D('userinfo_diagnosis_trade');	
		
		
            $UInfoDiagTS = $UInfoDiagTrade_ds->where('id=' . $tsid)->find();	
		if(strlen($UInfoDiagTS['acpt_doctor']) < 21)  
		{
                        $a=explode(';',ltrim($UInfoDiagTS['acpt_doctor'],';'));
                        if(in_array($doctorid,$a)){
                            $this->echoJson(array('result' => 1, 'oper' => '你已经接过诊'));	
                        }
			$new_acpt_doctor = $UInfoDiagTS['acpt_doctor'] . ";" . $doctorid;
			$UInfoDiagTrade_ds->where('id='.$tsid)->setField('acpt_doctor', $new_acpt_doctor);
			$time = date('Y-m-d H:i:s',time());
			$UInfoDiagTrade_ds->where('id='.$tsid)->setField('acpt_time', $time);			
		
			//消息中心记录,提醒 病人端调用 getA_Dct_Admission，建议再还调用 get_AdmissionDctList
		/*	$temp_info = D('temp_info'); 
			$data['uid'] = $UInfoDiagTS['userid'];
			$data['attach'] = $doctorid;
			$data['time'] =  date('Y-m-d H:i:s',time());
			$data['expire_time'] = time()+3600*24*3;//3天失效。
			$temp_info->add($data);	*/

			$data2['uid'] = $UInfoDiagTS['userid'];
			$data2['msgid'] ='6';
			$data2['todo'] ='getA_Dct_Admission';		
			$data2['time'] =time();			
			$data2['timex'] =date("Ymd H:i:s",$data2['time']); //可读形式	
			$heartbeatmsg_ds = D('heartbeat_msgtable');
			$heartbeatmsg_ds->add($data2);			
            //病历标志位：
			$dataX['status'] = 'A';	
			$re = $UInfoDiag_ds->where('userid='.$UInfoDiagTS['userid'])->save($dataX);	
		}
         $this->Jpush("有医生接诊,请查看",array('tag'=>array($UInfoDiagTS['userid'])));        
       $this->echoJson(array('result' => 0, 'oper' => 'OK'));		
	}	
	//====================================================================================
	//病人端获取到“医生接诊”信息提示
	//http://121.40.78.46/tb/index.php?m=Home&c=App&a=getA_Dct_Admission&uid=11
	//uid：病人id	
	public function getA_Dct_Admission()
	{	
	    $uid = intval(I('request.uid'));
		
		$temp_info = D('temp_info'); 
		$acpt_doctor =  $temp_info->where('uid='. $uid)->find();
		if($acpt_doctor == null)
		{
			$acpt_doctor ="";
		}
		else
		{
			$acpt_doctor['doctor'] = $acpt_doctor['attach'];
			unset($acpt_doctor['uid']);
			unset($acpt_doctor['expire_time']);				
		}			

        $this->echoJson(array('result' => 0, 'acpt_doctor' => $acpt_doctor));//先返回整条记录		
	}		
	//====================================================================================
	//病人端获取到接诊的所有医生 --医生列表。
	//http://121.40.78.46/tb/index.php?m=Home&c=App&a=get_AdmissionDctList&uid=11
	//uid：病人id	
	public function get_AdmissionDctList()
	{	
	    $userid = intval(I('request.uid'));
		
		$UInfoDiagTrade_ds = D('userinfo_diagnosis_trade');
                $doctor=D("doctor");
                $Hospital=D("Hospital");
        $UInfoDiagTS = $UInfoDiagTrade_ds->where("userid=" . $userid . " and status!='H'")->find();
		if($UInfoDiagTS==null)
		{
			$UInfoDiagTS = '';
		}
                if($UInfoDiagTS['acpt_doctor']!=''){
                    $arr=explode(";",ltrim($UInfoDiagTS['acpt_doctor'],";"));
                    $arr= array_unique($arr);
                    $temp=array();
                    $test=array();
                    foreach($arr as $k=>$v){
                        
                        $r=$doctor->where("id=".$v)->find();
                        if($r['img']!=null){
                            $temp[$k]['image']='http://img.cndoc.ivf-bb.com/'.$r['img'];
                    
                        }else{
                            $temp[$k]['image']="";
                        }
                        $rrr=$Hospital->where("id=".$r['hospital_id'])->find();
                        $temp[$k]['id']=$r['id'];
                        $temp[$k]['name']=$r['name'];
                        $temp[$k]['doc']=$rrr['name'];
                    }
                    if($UInfoDiagTS['deal_doctor']!=0){
                            
                            $r1=$doctor->where("id=".$UInfoDiagTS['deal_doctor'])->find();
                            if($r1['img']!=null){
                                $test[0]['image']='http://img.cndoc.ivf-bb.com/'.$r1['img'];
                            }else{
                                $test[0]['image']="";
                            }
                            $rrr=$Hospital->where("id=".$r1['hospital_id'])->find();
                            $test[0]['id']=$r1['id'];
                            $test[0]['name']=$r1['name'];
                            $test[0]['doc']=$rrr['name'];
                       $UInfoDiagTS['acpt_doctor']=$test;
                    }else{
                        $UInfoDiagTS['acpt_doctor']=$temp;
                    }
                }
        $this->echoJson(array('result' => 0, 'UInfoDiagTS' => $UInfoDiagTS));//先返回整条记录		
	}	
	//====================================================================================
	//病人端选择了一个医生。直接调用那个加医生的功能就可以了。
	//http://121.40.78.46/tb/index.php?m=Home&c=App&a=AcceptOneDoctor&uid=11&doctorid=10000005
	//uid：病人id	
	//doctorid: 医生id
	public function AcceptOneDoctor()
	{	
		$uid = I('request.uid');
                $doctorid = I('request.doctorid');	
		
		$user_ds = D('User');	
		$UInfoDiag_ds = D('userinfo_diagnosis');
		$UInfoDiagTrade_ds = D('userinfo_diagnosis_trade');
		
		$data['deal_doctor'] = $doctorid;
		$data['deal_time'] = date('Y-m-d H:i:s',time());
		$re = $UInfoDiagTrade_ds->where("userid=".$uid . " and status!='H'")->save($data);
		
		$dataX['status'] = 'D';	
		$re = $UInfoDiag_ds->where('userid='.$uid)->save($dataX);
		
		//真扣款了。
		$user_ds->where('id='.$uid)->setField('money_freeze',0);	//-100	
		$this->Jpush("有病人同意接诊",array('tag'=>array($doctorid)),"doctor");
		$this->echoJson(array('result' => 0, 'oper' => 'OK'));			
	}		
	
	
	
	
   //====================================================================================
    //用户登录后操作统一接口，好象现在没用到。
	//输入输出: uid
	//tag:??
	//http://121.40.78.46/tb/index.php?m=Home&c=App&a=checkUserTag&uid=6&tag=1
    protected function checkUserTag(){
    	$uid = intval(I('request.uid'));
    	$tag = I('request.tag');
    	$user_login_ds = D('UserLogin');
    	$user = $user_login_ds->where('uid='.$uid)->find();
    	if ($user == null){
    		$this->echoJson(array('result' => 1, 'reason' => '用户信息未找到'));
    		exit;
    	}
    	
    	if  ($user['login_tag'] !== $tag){
    		$this->echoJson(array('result' => 1, 'reason' => '非法登录: 用户TAG有误'));
    		exit;
    	}
    	
    	if ($user['expired_time'] < time()){
    		$this->echoJson(array('result' => 1, 'reason' => '登录超时，请重新登录'));
    		exit;
    	}
    	return $uid;
    } 
	
	
	
	///=======以下无用===============================
	
     /**
     * 判断二进制文件格式 (文件类型)，返回文件后缀
     * @param  string $file 二进制流
     * */
    function filefix($file){
        $bin = file_get_contents($file, 2); //只读2字节
        //对二进制解包 unpack
        $str = @unpack("C2chars", $file);    
        //读取二进制判断什么格式文件
        $typecode = intval($str['chars1'].$str['chars2']);
        $filetype = '';
        switch ($typecode) {
            case 8075:
                $filetype = 'zip';break;
            case 255216:
                $filetype = 'jpg';break;
            case 7173:
                $filetype = 'gif';break;
            case 1310:
                $filetype = 'jpg';break;
            default:
                $filetype = $typecode;break;
        }
        //解包文件夹，和文件名的信息
        return $filetype;
    }    
    
    
        /*************************************************************
    * 二进制流转入成文件
    * $data  二进制流数据
    * $filepath 存放的文件夹
    * $filename 存放的文件名
    *************************************************************/
    function binaryfile($data, $filepath, $filename){
        //转成数组
        $pth = explode("/",$filepath);
        $mydir='';
        //循环文件夹几层创建对应文件夹
        for($i=0;$i<count($pth)-1;$i++){
        
            if(!$pth[$i]) continue;
            $mydir .= $pth[$i]."/";
            //dump($mydir);
            //判断指定的文件夹是否存在，无就新建
            if((!is_dir($mydir) && @mkdir($mydir,0777))){
                @chmod($mydir,0777);
            }
        }
        //生成图片存放路径
        $file_path = $filepath.'/'.$filename;
        //echo $serpath.$file_path;
        //将POST过来的二进制数据直接写入文件.
        $ret = array();
        $ret[0] = file_put_contents('./'.$file_path,$data);
        $ret[1] = $filepath;
        $ret[2] = $filepath.$filename;
        return $ret;
    }
    
	
	
//---------------------------------------------------------------------------------
    
    
    
    //---------------------------------------------------------------------------------
    
    
    //获取好友信息
    //id是自己的id
    //uid是好友的id
    function getUserInfo(){
        $id=I("request.id");
        $uid=I("request.uid");
        $user=D("User");
        $res=$user->where('id='.$uid)->field("id,name,truename,telephone,register_time,image,birthday,sex,good_ids")->select();
        if(!$res){
            $this->echoJson(array('result' => 1, 'reason' => "没有该用户"));
            exit;
            
        }
        
        if($res[0]['image']!=null){
            $res[0]['image']=array(rtrim("http://img.user.ivf-bb.com/".$res[0]['image'],','));
        }else{
            $res[0]['image']=array();
        }
        $r=$user->where('id='.$id)->find();
        $a=explode(',',rtrim($r['good_ids'],','));
        if(in_array($uid,$a)){
            $res[0]['is_gz']=1;
            
        }else{
            $res[0]['is_gz']=0;
            
        }
        
        $this->echoJson(array('result' => 0, 'userinfo' => $res));
        
        
    }
    //关注好友,取消关注
    function gzhaoyou(){
        $id=  intval(I("request.id"));
        $uid=intval(I("request.uid"));
        $type=I("request.type");
        $user=D("User");
        $res=$user->where('id='.$id)->field("id,name,truename,telephone,register_time,image,birthday,sex,good_ids")->select();
        if(!$res){
            $this->echoJson(array('result' => 1, 'reason' => "没有该用户"));
            exit;
            
        }
        if($type==1){
                $arr=explode(',',rtrim($res[0]['good_ids'],','));
                foreach($arr as $k=>$v){
                    if($uid==$v){
                        unset($arr[$k]);
                    }
                }
                $st=implode(',', $arr);
                $r=$user->where('id = '.$id)->setField('good_ids',$st.',');
                if(!$r){
                    $this->echoJson(array('result' => 1, 'reason' => "系统出错"));
                    exit;
                }
                $this->echoJson(array('result' => 0, 'reason' => "ok"));
                exit;
        }
        $a=explode(',',rtrim($res[0]['good_ids'],','));
        if(in_array($uid,$a)){
            $this->echoJson(array('result' => 1, 'reason' => "你已经关注过"));
            exit;
        }else{
            $r=$user->where('id = '.$id)->setField('good_ids',$res[0]['good_ids'].$uid.',');
            if(!$r){
                $this->echoJson(array('result' => 1, 'reason' => "系统出错"));
                exit;
            }
            $this->echoJson(array('result' => 0, 'reason' => "ok"));
            exit;
        }
        
    
    }
    //获取好友列表
    function get_UserList(){
        $id=I("request.id");
        $type=I("request.type");
        $count=I("request.count");
        $page=I("request.page");
        $user=D("User");
        $res=$user->where('id='.$id)->field("id,name,truename,telephone,register_time,image,birthday,sex,good_ids")->select();
        if(!$res){
            $this->echoJson(array('result' => 1, 'reason' => "没有该用户"));
            exit;
            
        }
        
        if(empty($res[0]['good_ids'])&&$type==1){
            $where='';
        }else if(empty($res[0]['good_ids'])&&$type==0){
            $this->echoJson(array('result' => 0, 'info' => ""));exit;
        }else{
            $arr=explode(',',$res[0]['good_ids']);
            array_pop($arr);
            if($type==1){
                $temp='not in';
            }else{
                $temp='in';
            }
            $where=array("id"=>array($temp,$arr));
        }
        
        $r=$user->where($where)->field("id,name,truename,telephone,register_time,image,birthday,sex,good_ids")->limit(($page-1)*$count,$count)->select();
        if(!$r){
            $this->echoJson(array('result' => 1, 'reason' => "没有该用户"));
            exit;
            
        }
        foreach($r as &$vv){
//                    if($vv['image']!=null&&$vv['id']>100000000){
//                        $vv['image']=array($_SERVER["HTTP_HOST"] . "/tb/imagecn_doc/".$vv['image']);
//                    }elseif($vv['image']!=null&&$vv['id']<100000000){
                        $vv['image']=array(rtrim("http://img.user.ivf-bb.com/".$vv['image'],','));
//                    }else{
//                        $vv['image']=array();
//                    }
        }
        $this->echoJson(array('result' => 0, 'info' => $r));
    }
    //发表动态
    function relese_obj(){
        $data['uid']=intval(I("request.uid"));
        $data['content']=I("request.content");
        $data['position']=I("request.position");
        $data['create_time']=  intval(I("request.key"));
        $pyq_content=D("PyqContent");
        $res=$pyq_content->add($data);
        if(!$res){
            $this->echoJson(array('result' => 1, 'reason' => "添加失败"));
        }else{
            $this->echoJson(array('result' => 0, 'reason' => "添加成功"));
        }
    }
    //上传朋友圈图片
    public function upload_pyq_img(){
//            $uptypes=array(  
//			'image/jpg',  
//			'image/jpeg',
//			'image/pjpeg',
//			'image/png', 	
//			'image/bmp',
//			'image/gif',
//			'audio/amr',
//		); 
//		$max_file_size=50000000000000000;     //2M,上传文件大小限制, 单位BYTE   
		$type = intval(I('request.type'));
		$uid = intval(I('request.uid'));
		$data['create_time']=  intval(I("request.key"));
                $setting=C('UPLOAD_SITEIMG_QINIU');
                $setting['driverConfig']['domain']='img.other.ivf-bb.com';
                $setting['driverConfig']['bucket'] = 'imageother';
//                $setting['saveName'] = array ('uniqid', 'imagePYQ_');
                $setting['subName'] = 'imagePYQ/'.date('Y-m-d',time());
                $Upload = new \Think\Upload($setting);
                $info = $Upload->upload($_FILES);
                $t=  date('Y-m-d',time());
                $name='';
                foreach ($info as $v){
                    $name.=$t.'/'.$v['savename'].',';
                }

                    
                    //添加数据库
                    $data['uid']=intval($uid);
                    $data['imgs']=$name;
                    $PyqImgs=D("PyqImgs");
                    $res=$PyqImgs->add($data);
                    if(!$res){
                        $this->echoJson(array('result' => 1, 'reason' => "添加失败"));
                    }else{
                        $this->echoJson(array('result' => 0, 'reason' => "添加成功"));
                    }
                    
    }
    //朋友圈动态列表
    function obj_list(){
        $myuid=I("request.myuid");
        $id=I("request.id");
        $count=I("request.count");
        $page=I("request.page");
        $like=I("request.so");
        $user=D("user");
        $res=$user->where('id='.$id)->find();
        if(!$res){
            $this->echoJson(array('result' => 1 , 'reason' => "没有此用户"));exit;
        }
        //按照老总要求修改接口为展示所有人动态
//        if(empty($res[0]['good_ids'])){
//            $this->echoJson(array('result' => 0, 'info' => ""));
//            exit;
//        }
//        $str=rtrim($res[0]['good_ids'],',');
//        $arr=explode(',', $str);
        $pyq_content=D("PyqContent");
        $where='';
        if($myuid!=''){
            $ress=$user->where('id='.$myuid)->find();
            if(!$ress){
                $this->echoJson(array('result' => 1 , 'reason' => "没有此用户"));exit;
            }
            $where='uid='.$myuid." and is_ran=0";
        }else{
            $where="is_ran=0";
        }
        //按照老总要求修改接口为展示所有人动态
        //$r=$pyq_content->where(array("uid"=>array('in',$arr)))->where("content Like '%".$like."%'")->order('create_time DESC')->limit(($page-1)*$count,$count)->select();
        $r=$pyq_content->where($where)->order('create_time DESC')->limit(($page-1)*$count,$count)->select();
        foreach($r as &$v){
            $rrr=$user->where('id='.$v['uid'])->field("name,truename,image")->select();
            if(empty($v['zan_ids'])){
                $v['zan_ids']=array();
            }else{
                $result=$user->where('id in ('.rtrim($v['zan_ids'],',').')')->field("id,name,truename")->select();
                $v['zan_ids']=$result;
            }
            $v['name']=$rrr[0]['name'];
            $v['truename']=$rrr[0]['truename'];
            $v['image']=rtrim("http://img.user.ivf-bb.com/".$rrr[0]['image'],',');
            $imgs=D('PyqImgs');
            $rr=$imgs->where("uid =".$v['uid']." and create_time =".$v['create_time'])->field('imgs')->select();
            if(empty($rr)){
                $v['imgs']=array();
            }else{
                $array=explode(',',rtrim($rr[0]['imgs'],','));
                foreach($array as &$vv){
                    $vv="http://img.other.ivf-bb.com/imagePYQ/".$vv;
                }
                $v['imgs']=$array;
            }
            //评论数据
            $pyqcomment=D("PyqComment");
            $r1=$pyqcomment->where("cid=".$v['id'])->select();
            foreach ($r1 as &$vv){
                $user=D("user");
                $res=$user->where('id='.$vv['uid'])->field('name,truename')->select();
                if(!$res){
                    $this->echoJson(array('result' => 1, 'reason' => "没有此用户"));exit;
                }
                $vv['u_name']=$res[0]['name'];
                $vv['u_truename']=$res[0]['truename'];
                if($vv['pid']!=0){
                    $res=$user->where('id='.$vv['pid'])->field('name,truename')->select();
                    if(!$res){
                        $this->echoJson(array('result' => 1, 'reason' => "没有此用户"));exit;
                    }
                    $vv['p_name']=$res[0]['name'];
                    $vv['p_truename']=$res[0]['truename'];
                }else{
                    $vv['p_name']='';
                    $vv['p_truename']='';

                }
            }
            $v['comment_list']=$r1;
            
        }
        $this->echoJson(array('result' => 0, 'info' => $r));
    }
    //删除朋友圈动态
    public function del_obj(){
        $id=I("request.id");
        $uid=I("request.uid");
        $pyq_content=D("PyqContent");
        $r=$pyq_content->where("id=".$id." and uid=".$uid)->find();
        if(!$r){
            $this->echoJson(array('result' => 1 , 'info' => "没有此信息"));exit;
        }
        $rr=$pyq_content->where("id=".$id." and uid=".$uid)->setField("is_ran",1);
        $this->echoJson(array('result' => 0 , 'info' => "ok"));exit;
    }
    
    
    //朋友圈发表评论接口
    function pyq_comment(){
        $did=intval(I("request.did"));
        $content=I("request.content");
        $uid=intval(I("request.uid"));
        $pid=intval(I("request.pid"));
        $user=D("user");
        $res=$user->where('id='.$uid)->select();
        if(!$res){
            $this->echoJson(array('result' => 1, 'reason' => "没有此用户"));exit;
        }
        if($pid!=0){
            $res=$user->where('id='.$pid)->select();
            if(!$res){
                $this->echoJson(array('result' => 1, 'reason' => "没有此用户"));exit;
            }
        }
        $PyqContent=D("PyqContent");
        $res=$PyqContent->where('id='.$did)->select();
        $tempid=$res[0]['uid'];
        if(!$res){
            $this->echoJson(array('result' => 1, 'reason' => "没有此动态"));exit;
        }
        $pyqcomment=D("PyqComment");
        $data['cid']=$did;
        $data['content']=$content;
        $data['uid']=$uid;
        $data['pid']=$pid;
        $data['create_time']=time();
        $res=$pyqcomment->add($data);
        if(!$res){
            $this->echoJson(array('result' => 1, 'reason' => "添加数据失败"));exit;
        }
        //增加评论数
        if($pid==0){
            $pyq_content=D("PyqContent");
            $r=$pyq_content->where("id =".$did)->setInc('content_count');
            if(!$r){
                $this->echoJson(array('result' => 1, 'reason' => "添加评论数据失败"));exit;
            }
        }
        //推送
        if($pid==0){
            if($tempid>100000000){
                $this->Jpush("您有新的评论,请查看",array('tag'=>array("$tempid")),"doctor");
            }else{
                $this->Jpush("您有新的评论,请查看",array('tag'=>array("$tempid")));
            }
        }else{
            if($pid>100000000){
                $this->Jpush("您有新的评论,请查看",array('tag'=>array("$pid")),"doctor");
            }else{
                $this->Jpush("您有新的评论,请查看",array('tag'=>array("$pid")));
            }
            
        }
        
        $this->echoJson(array('result' => 0, 'reason' => "ok"));
    }
    //评论列表
    function pyq_comment_list(){
        $cid=intval(I("request.cid"));
        $pyq_comment=D("PyqComment");
        $count=I("request.count");
        $page=I("request.page");
        $r=$pyq_comment->where("cid=".$cid)->order('create_time DESC')->limit(($page-1)*$count,$count)->select();
        foreach ($r as &$v){
            $user=D("user");
            $res=$user->where('id='.$v['uid'])->field('name,truename')->select();
            if(!$res){
                $this->echoJson(array('result' => 1, 'reason' => "没有此用户"));exit;
            }
            $v['u_name']=$res[0]['name'];
            $v['u_truename']=$res[0]['truename'];
            if($v['pid']!=0){
                $res=$user->where('id='.$v['pid'])->field('name,truename')->select();
                if(!$res){
                    $this->echoJson(array('result' => 1, 'reason' => "没有此用户"));exit;
                }
                $v['p_name']=$res[0]['name'];
                $v['p_truename']=$res[0]['truename'];
            }else{
                $v['p_name']='';
                $v['p_truename']='';
                
            }
        }
        //增加点击数
        if($page==1){
            $pyq_content=D("PyqContent");
            $rr=$pyq_content->where("id =".$cid)->setInc('link_count');
            if(!$rr){
                $this->echoJson(array('result' => 1, 'reason' => "添加评论数据失败"));exit;
            }
        }
        $this->echoJson(array('result' => 0, 'info' => $r));
    }
    
    //诊所列表
    function clinic_list($zid=-1){
        $Hospital=D("Hospital");
        $count=I("request.count");
        $page=I("request.page");
        if($zid==-1){
            $where="country='美国'";
        }else{
            $where="zid = ".$zid;
        }
        $res=$Hospital->where($where)->limit(($page-1)*$count,$count)->field("id,name,logo_img,abstract,address,telephone,descrip")->select();
        if(!$res){
            $this->echoJson(array('result' => 1, 'reason' => "查询失败"));exit;
        }
        foreach($res as &$v){
            if($v['logo_img']==null){
                $v['logo_img']='';
            }else{
                $v['logo_img']="http://img.other.ivf-bb.com/".$v['logo_img'];
            }
        }
        $this->echoJson(array('result' => 0, 'info' => $res));
    }
    //诊所附近的酒店type1为展示type为2为商品id
    //根据距离排序
    function nearby_hospital($type,$id,$opt=1){
        $Hotel=D("Hotel");
        $count=I("request.count");
        $page=I("request.page");
        if($page<1){
            $this->echoJson(array('result' => 1, 'info' => "页数错误"));exit;
        }
        
        if($type==1){
            $hospital=D("Hospital");
            $re=$hospital->where("id=".$id)->find();
            if(!$re){
                $this->echoJson(array('result' => 1, 'info' => "参数错误"));exit;
            }
            $where='hid='.$id;
        }elseif($type==2){
            $shop=D("ShopBase");
            $re=$shop->where("id=".$id)->find();
            if(!$re){
                $this->echoJson(array('result' => 1, 'info' => "参数错误"));exit;
            }
            $where='shop_id='.$id;
        }
        $res=$Hotel->where($where)->limit(($page-1)*$count,$count)->order("distance asc")->select();
        if(!$res){
            $this->echoJson(array('result' => 1, 'info' => "查询失败"));exit;
        }
        foreach($res as $k=>&$v){
            $v['juli']=$v['distance'];
            if($v['imgs']==null){
                $v['imgs']=array();
            }else{
                $arr=explode(",", rtrim($v['imgs'],","));
                foreach($arr as &$vv){
                    $vv="http://img.hotel.ivf-bb.com/".$vv;
                }
                $v['imgs']= $arr;
            }
        }
        $this->echoJson(array('result' => 0, 'info' => $res));
    }
    
    //诊所附近的酒店type1为展示type为2为商品id
    //根据经纬度(暂时没收集到经纬度)
//    function nearby_hospital($type,$id,$opt=1){
//        $Hotel=D("Hotel");
//        $count=I("request.count");
//        $page=I("request.page");
//        $res=$Hotel->where("country='美国'")->limit(($page-1)*$count,$count)->select();
//        if(!$res){
//            $this->echoJson(array('result' => 1, 'info' => "查询失败"));exit;
//        }
//        if($type==1){
//            $hospital=D("Hospital");
//            $re=$hospital->where("id=".$id)->find();
//            if(!$re){
//                $this->echoJson(array('result' => 1, 'info' => "参数错误"));exit;
//            }
//        }elseif($type==2){
//            $shop=D("ShopBase");
//            $re=$shop->where("id=".$id)->find();
//            if(!$re){
//                $this->echoJson(array('result' => 1, 'info' => "参数错误"));exit;
//            }
//        }
//        foreach($res as $k=>&$v){
//            $v['juli']=$this->getDistance($re['lat'],$re['lng'],$v['lat'],$v['lng']);
//            $sortdistance[$k] = $v['juli'];
//            $levels[$k] = $v['level'];
//            if($v['imgs']==null){
//                $v['imgs']=array();
//            }else{
//                $arr=explode(",", rtrim($v['imgs'],","));
//                foreach($arr as &$vv){
//                    $vv=$_SERVER["HTTP_HOST"] . "/tb/image_hotel/".$vv;
//                }
//                $v['imgs']= $arr;
//            }
//        }
//        if($opt==1){
//            array_multisort($sortdistance,SORT_ASC,$res);
//        }elseif($opt==2){
//            array_multisort($levels,SORT_DESC,$res);
//        }
//        $this->echoJson(array('result' => 0, 'info' => $res));
//    }
//    //根据经纬度得出距离
//    private function getDistance($lat1, $lng1, $lat2, $lng2) {
//        //地球半径
//        $R = 6378137;
//        //将角度转为狐度
//        $radLat1 = deg2rad($lat1);
//        $radLat2 = deg2rad($lat2);
//        $radLng1 = deg2rad($lng1);
//        $radLng2 = deg2rad($lng2);
//        //结果
//        $s = acos(cos($radLat1)*cos($radLat2)*cos($radLng1-$radLng2)+sin($radLat1)*sin($radLat2))*$R;
//        //精度
//        $s = round($s* 10000)/10000;
//        return  round($s);
//    }
    //朋友圈取消点赞/点赞接口
    function pyq_zan(){
        $type=intval(I("request.type"));
        $uid=I("request.uid");
        $id=intval(I("request.id"));
        $PyqContent=D("PyqContent");
        $user=D("user");
        $rr=$user->where('id='.$uid)->field("id,name,truename")->select();
        if(!$rr){
            $this->echoJson(array('result' => 1, 'reason' => "没有此用户"));exit;
        }
        $res=$PyqContent->where("id =".$id)->getField('zan_ids');
        if($type==1){
            if(empty($res)){
                $r=$PyqContent->where("id =".$id)->setField('zan_ids',$uid.',');
                if(!$r){
                    $this->echoJson(array('result' => 1, 'info' => "添加失败"));exit;
                }else{
                    $this->echoJson(array('result' => 0, 'info' => $rr)); exit;       
                }
            }else{
                $a=explode(',',rtrim($res,','));
                if(in_array($uid,$a)){
                    $this->echoJson(array('result' => 1, 'info' => "你已经为此动态点过赞了"));exit;
                }else{
                    $r=$PyqContent->where("id =".$id)->setField('zan_ids',$res.$uid.','); 
                    if(!$r){
                        $this->echoJson(array('result' => 1, 'info' => "添加失败"));exit;
                    }else{
                        $this->echoJson(array('result' => 0, 'info' => $rr)); exit;       
                    }
                }
            }
            
        }else{
             $a=explode(',',rtrim($res,','));
            if(in_array($uid,$a)){
                    $this->echoJson(array('result' => 1, 'info' => "你还没有点赞"));exit;
            }else{
                $r=$PyqContent->where("id =".$id)->setField('zan_ids',str_replace($uid.',','',$res)); 
                if(!$r){
                    $this->echoJson(array('result' => 1, 'info' => "取消失败"));exit;
                }else{
                        $this->echoJson(array('result' => 0, 'info' => $rr)); exit;       
                }
            }
        }
    }
    //获取机构列表
    function get_surrogate_mechanism_list(){
        
        $SurrogateMechanism=D("SurrogateMechanism");
        $count=intval(I("request.count"));
        $page=intval(I("request.page"));
        $r=$SurrogateMechanism->limit(($page-1)*$count,$count)->select();
        if(!$r){
            $this->echoJson(array('result' => 1, 'info' => "没有数据"));exit;
        }
        foreach($r as &$v){
            $v['img']="http://img.other.ivf-bb.com/imageDYJG/".$v['img'];
            $v['team_dis']=  explode("|", $v['team_dis']);
            $v['service_content']=  explode("|", $v['service_content']);
        }
        $this->echoJson(array('result' => 1, 'info' => $r));exit;
    }
    //广告接口
    function banner_list(){
        $Banner=D("Banner");
        $r=$Banner->order('orders ASC')->limit("0,6")->select();
        if(!$r){
            $this->echoJson(array('result' => 1, 'info' => "没有数据"));exit;
        }
        foreach ($r as &$v){
            $v['img']="http://img.other.ivf-bb.com/imageBANNER/".$v['img'];
        }
        $this->echoJson(array('result' => 1, 'info' => $r));
    }
    //=====================================================================================
//增加BBS群聊对象。第一次增加时，服务器需要插入群id
//仿照微信: 用户a在跟用户b聊天时，把用户c拉进来，此时会形成一个群。这时调用: 
//http://121.40.78.46/tb/index.php?m=Home&c=App&a=addgroupChatobject&groupid=-1&objectid=a;b;c
//此后群内任何人拉朋友进群时，调用: 
//http://121.40.78.46/tb/index.php?m=Home&c=App&a=addgroupChatobject&groupid=6&objectid=4  
//groupid:聊天室id,第一次加人时传入-1,此时，objectid 是三个人的id，分号隔开
//objectid:聊天对象（用户或医生）的id，即被拉入群的人的id
//简单起见，与人聊天或拉人入群，不需要对方同意。直接就说话了。
	public function addBBSgroup()
    {
$myfilex = fopen("qq-addgroupChatobject.txt", "w") or die("Unable to open file!");	
		
		$groupid=I('request.groupid');
		$userdoctor_id=I('request.objectid');
fwrite($myfilex, "\ngroupid=" .$groupid);
fwrite($myfilex, "\nuserdoctor_id=" .$userdoctor_id);
		
		$groupchat_id_ds = D('groupchat_id');
		$user_ds = D('User');
		$doctor_ds = D('Doctor');	
		$chatlist_ds = D('chatlist');		
		
		if($groupid == -1 || $groupid==0)//第一次，建立群.
		{
			$data['userdoctor_ids'] = ";" .$userdoctor_id . ";" ;	//前后加上分号		

			//拼群组名称: 
			$groupname = '群:';			            
			$speakeridarr = explode(";",$userdoctor_id);
			$ii=0;
		
			foreach ($speakeridarr as $speakerid)
			{			
				$ii = $ii+1;
				if($ii>4){break;} //最多4个。
				if($speakerid > 100000000)
				{
					$CtObj   = $doctor_ds->where('id='.$speakerid)->find();					
				}
				else
				{
					$CtObj   = $user_ds->where('id='.$speakerid)->find();						
				}
				$groupname = $groupname .$CtObj['name']. "," ;
			}	//for	
			$data['groupname'] = $groupname;//最后还有个逗号，算了。
			
			$groupchat_id = $groupchat_id_ds->add($data);	
			
			foreach ($speakeridarr as $speakerid)
			{		
				/*
				if($speakerid > 100000000)
				{
					$CtObj   = $doctor_ds->where('id='.$speakerid)->find();
					
					$newids  = $CtObj['groupchatids'] . $groupchat_id  . ";" ;	
					$result1 = $doctor_ds->where('id='.$speakerid)->setField('groupchatids', $newids);						
				}
				else
				{
					$CtObj   = $user_ds->where('id='.$speakerid)->find();	

					$newids  = $CtObj['groupchatids'] . $groupchat_id  . ";" ;	
					$result1 = $user_ds->where('id='.$speakerid)->setField('groupchatids', $newids);						
				}
				//$groupname = $groupname .$CtObj['name']. "," ;	*/	
                                $chatlistr['myuid']	=$speakerid;
				$chatlistr['groupid']	=$groupchat_id;
				$chatlistr['uid']	= -1;
				$chatlistr['objName']	=$groupname;
				$chatlistr['speaktime']	=time();
				$chatlist_ds->add($chatlistr);				
			}	//for			
 	
			$this->echoJson(array('result' => 0, 'groupchat_id' => $groupchat_id, 'groupname' => $groupname));
		}
		else  //群早已存在
		{
                    
                    //先找人
                    if($userdoctor_id > 100000000)
				{
					$CtObj   = $doctor_ds->where('id='.$userdoctor_id)->find();					
				}
				else
				{
					$CtObj   = $user_ds->where('id='.$userdoctor_id)->find();						
				}
		    //在群组表里增加聊天人id
			$rec     = $groupchat_id_ds->where('groupchat_id='.$groupid)->find();
                        $a=explode(';',  rtrim(ltrim($rec['userdoctor_ids'],';'),';'));
                        if(in_array($userdoctor_id,$a)){
                            $this->echoJson(array('result' => 0, 'groupchat_id' => $groupid, 'groupname' => $rec['groupname']));exit;
                        }
			$newids  = $rec['userdoctor_ids']  . $userdoctor_id . ";";			

			$result1 = $groupchat_id_ds->where('groupchat_id='.$groupid)->setField('userdoctor_ids', $newids);
			//增加群名称
                        $newgroupname  = $rec['groupname']  . $CtObj['name'] . ",";
			$result1 = $groupchat_id_ds->where('groupchat_id='.$groupid)->setField('groupname', $newgroupname);
			//对个人，记录群id
			/*			
		    $rec     = $user_ds->where('id='.$userdoctor_id)->find();
			$newids  = $rec['groupchatids'] . $groupid  . ";" ;	
			$result1 = $user_ds->where('id='.$userdoctor_id)->setField('groupchatids', $newids);
			*/			
			$chatlistr['myuid']	=$userdoctor_id;
			$chatlistr['groupid']	=$groupid;
			$chatlistr['uid']	= -1;
			$chatlistr['objName']	=$rec['groupname'];
			$chatlistr['speaktime']	=time();
			$chatlist_ds->add($chatlistr);			
			$groupname = $rec['groupname'];//就这样吧。不再追加人名了。
		    $this->echoJson(array('result' => 0, 'groupchat_id' => $groupid, 'groupname' => $groupname));
		} //else
//fclose($myfilex);		
	}
    
    //H5支付接口
    function html_order(){
        $uid = I('request.uid');
	$orderNo = I('request.orderNo');
	$addmoney = I('request.addmoney');
        if($addmoney<100){
            $this->echoJson(array('result' => 1, 'info' => "最少100"));
        }
	if($addmoney == '' || $addmoney == null){
	     $this->echoJson(array('result' => 1, 'info' => "金额不能为空"));
	}else{
		$url = "http://ivf-bb.com/tb/smc_html5_new/index.php?uid=" . $uid . "&orderNo=".$orderNo."&addmoney=" . $addmoney;
	}
	$this->echoJson(array('result' => 0, 'url' => $url));
        
    }
    //H5查询支付结果
    function html_orderres(){
        $uid = I('request.uid');
        $addmoney = I('request.addmoney');
        $orderNo = I('request.orderNo');
        $MoneyLog=D("MoneyLog");
        $r=$MoneyLog->where("uid=".$uid." and order_no='".$orderNo."'")->select();
        if(!$r){
            $this->echoJson(array('result' => 1, 'info' => "支付失败"));exit;
        }else{
            $this->echoJson(array('result' => 0, 'info' => "支付成功"));exit;
        }
    }
    //生成二维码
    public function qrcode(){
        //判断有无此群聊
        $uid=I('request.uid');
        $bid=I('request.bid');
        $groupchat_id_ds = D('groupchat_id');
        $user_ds = D('User');
	$doctor_ds = D('Doctor');
        $chatlist_ds = D('chatlist');
        $res   = $groupchat_id_ds->where('bid='.$bid)->find();
        $gid='';
        if(!$res){
            $data['userdoctor_ids'] = ";" .$uid . ";" ;	//前后加上分号		

			//拼群组名称: 
			$groupname = '群:';			            
			$speakeridarr = explode(";",$uid);
			$ii=0;
		
			foreach ($speakeridarr as $speakerid)
			{			
                            
                                $ii = $ii+1;
				if($ii>4){break;} //最多4个。
				if($speakerid > 100000000)
				{
					$CtObj   = $doctor_ds->where('id='.$speakerid)->find();					
				}
				else
				{
					$CtObj   = $user_ds->where('id='.$speakerid)->find();						
				}
				$groupname = $groupname .$CtObj['name']. "," ;
			}	//for	
			$data['groupname'] = $groupname;//最后还有个逗号，算了。
			$data['bid']=$bid;
			$groupchat_id = $groupchat_id_ds->add($data);
                        foreach ($speakeridarr as $speakerid)
			{			
                                $chatlistr['myuid']	=$speakerid;
				$chatlistr['groupid']	=$groupchat_id;
				$chatlistr['uid']	= -1;
				$chatlistr['objName']	=$groupname;
				$chatlistr['speaktime']	=time();
				$chatlist_ds->add($chatlistr);
                        }
                        $gid=$groupchat_id;
            
        }else{
            $gid=$res['groupchat_id'];
        }
        $img = file_get_contents("http://139.196.5.206/tb/index.php?m=Home&c=Index&a=BBSqrcode&str=".$gid,true);
        header("Content-Type: image/jpeg;text/html; charset=utf-8");
        echo $img;
//        vendor('phpqrcode.phpqrcode');
//        //定义纠错级别
//
//        $errorLevel = "L";
//
//        //定义生成图片宽度和高度;默认为3
//        
//        $size = "4";
//        //调用QRcode类的静态方法png生成二维码图片//
//        $QRcode = new \QRcode();
//        
//        $content=$gid;
//
//        //调用QRcode类的静态方法png生成二维码图片//
//        $QRcode::png($content, false, $errorLevel, $size);
        //生成网址类型

//        $url.="http://baidu.com/12345647897897asdasdasdasdasdsad";
//
//        $QRcode::png($url, false, $errorLevel, $size);
    }
    //医生版推送
    //$content 推送内容
    //推送标示 all全部
    public function Jpush($content='您有新消息!',$receive = 'all',$type="",$m_type='1'){
        $fetion = new \Org\Util\JpushSend();
        if($type=="doctor"){
            $fetion->setOption();
        }
          //$receive = array('tag'=>array('123'));//标签
            //$receive = array('alias'=>array('1'),);//别名
            $m_txt = '123456789';
            $m_time = '600';        //离线保留时间
            $res=$fetion->send_pub($receive, $content ,$m_type, $m_txt ,$m_time); 
    }
    //返回国家的所有州
    public function american_state($cid=1){
        $State=D("State");
        if($cid==0){
            $r=$State->where("cid=".$cid)->order("convert(name using gb2312) ASC")->select();
        }elseif($cid==1){
            $r=$State->where("cid=".$cid)->order("convert(en_name using gb2312) ASC")->select();
        }
//        $rr=$hos->field("zid")->select();
//        
        $temp=array();
        foreach($r as $v){
            if($cid==0){
                $temp[]=$this->getFirstCharter($v['name']);
            }elseif($cid==1){
                $temp[]=$this->getFirstCharter($v['en_name']);
            }
        }
        $temp=array_unique($temp);
        $arr=array();
        foreach($temp as $vv){
            foreach($r as $vvv){
                if($cid==0){
                    if($this->getFirstCharter($vvv['name'])==$vv){
                        $arr[$vv][]=$vvv;
                    }
                }elseif($cid==1){
                    if($this->getFirstCharter($vvv['en_name'])==$vv){
                        $arr[$vv][]=$vvv;
                    }
                } 
            } 
        }
        if(!$r){
            $this->echoJson(array('result' => 1, 'info' => "失败"));exit;
        }else{
            $this->echoJson(array('result' => 0, 'info' => $arr));exit;
        }
    }
    
    //返回所有病人
    public function bin_list(){
        $user_ds = D('User');
        $res = $user_ds->where('id<100000000')->field('id,name,truename,telephone,image,birthday,sex')->select();
        if(!$res){
            $this->echoJson(array('result' => 1, 'info' => ""));exit;
        }
        foreach ($res as &$v){
            if($v['image']!=null){
                $v['image']=rtrim("http://img.user.ivf-bb.com/".$v['image'],',');
            }
        }
        $this->echoJson(array('result' => 0, 'info' => $res));exit;
    }
    
    
    //测试
//    public function tttt(){
//        $hos=D("hospital");
//        $doc=D("Doctor");
//        $res=$hos->select();
//        foreach($res as $v){
//            if($v['logo_img']!=null&&$v['country']=="美国"){
//                $Q=substr($v['logo_img'],0,-4);
//                $data['logo_img']=$Q;
//                $hos->where('id='.$v['id'])->save($data);
//            }
//            if($v['imgs']!=null){
//                $arr=explode(",",$v['imgs']);
//                foreach ($arr as &$vvv){
//                    if($vvv!=null){
//                        $t=substr($vvv,-4);
//                        $vvv=$vvv.$t;
//                    }
//                    if($vvv==null){
//                        unset($vvv);
//                    }
//                        
//                }
//                $da['imgs']=implode(",", $arr);
//                $hos->where('id='.$v['id'])->save($da);
//            }
//            $r=$doc->where("hospital_id=".$v['id'])->select();
//            if(!$r){
//                
//            }else{
//                foreach($r as $vv){
//                    if($vv['img']!=null){
//                        $tt=substr($vv['img'],-4);
//                        $opt['img']=$vv['img'].$tt;
//                        $doc->where("id=".$vv['id'])->save($opt);
//                    }
//                    
//                }
//                
//            }
//        }
//         
//    }
    //返回国家下面地区的所有诊所信息
    //id 地区id
    public function get_cn_hospitai(){
        $id=I("request.id");
        $hos=D("hospital");
        $doc=D("Doctor");
        $state=D("State");
        $res=$hos->where("zid=".$id)->order("orders desc")->select();
        if(!$res){
            $this->echoJson(array('result' => 1, 'info' => "没有该国家医院"));exit;
        }
        foreach($res as &$v){
            if($v['logo_img']!=null){
                $v['logo_img']="http://img.cnhos.ivf-bb.com/".$v['logo_img'];
            }
            if($v['imgs']!=null){
                $arr=explode(",",$v['imgs']);
                foreach ($arr as &$vvv){
                    if($vvv!=null){
                        $vvv="http://img.cnxxhos.ivf-bb.com/".$vvv;
                    }
                }
                $v['imgs']=$arr;
            }  else {
                $v['imgs']=array();
            }
            
            $r=$doc->where("hospital_id=".$v['id']." and auth_status=2")->select();
            if(!$r){
                $v['doc']=array();
            }else{
                foreach($r as &$vv){
                    if($vv['img']!=null){
                        $vv['img']='http://img.cndoc.ivf-bb.com/'.$vv['img'];
                    }
                    unset($vv['password']);
                }
                $v['doc']=$r;
            }
            
        }
        $this->echoJson(array('result' => 0, 'info' => $res));exit;
    }
    //通过医生id查找医院和医生信息
    public function get_by_docid($did=''){
        $hos=D("hospital");
        $doc=D("Doctor");
        $rr=$doc->where("id=".$did)->find();
        $res=$hos->where("id=".$rr['hospital_id'])->select();
        if(!$res){
            $this->echoJson(array('result' => 1, 'info' => "没有该医院"));exit;
        }
        foreach($res as &$v){
            if($v['logo_img']!=null){
                $v['logo_img']="http://img.cnhos.ivf-bb.com/".$v['logo_img'];
            }
            if($v['imgs']!=null){
                $arr=explode(",",$v['imgs']);
                foreach ($arr as &$vvv){
                    if($vvv!=null){
                        $vvv="http://img.cnxxhos.ivf-bb.com/".$vvv;
                    }
                }
                $v['imgs']=$arr;
            }  else {
                $v['imgs']=array();
            }
            $r=$doc->where("hospital_id=".$v['id']." and auth_status=2")->select();
            if(!$r){
                $v['doc']=array();
            }else{
                foreach($r as &$vv){
                    if($vv['img']!=null){
                        $vv['img']='http://img.cndoc.ivf-bb.com/'.$vv['img'];
                    }
                    unset($vv['password']);
                }
                $v['doc']=$r;
            }
            
        }
        $this->echoJson(array('result' => 0, 'info' => $res));exit;
    }
    
    //爬虫
    public function py(){
        if(empty($url))$url = "http://lifeivfcenter.com/";//需要采集链接的URL地址

	$site=substr($url,0,strpos($url,"/",8));

	$base=substr($url,0,strrpos($url,"/")+1);//文件所在目录

	$fp = fopen($url, "r" );//打开url地址页面

	while(!feof($fp))$contents.=fread($fp,1024);

	$pattern="|href=['\"]?([^ '\"]+)['\" ]|U";

	preg_match_all($pattern,$contents, $regArr, PREG_SET_ORDER);//使用正则匹配所有href=
        
        foreach($regArr as $k=>&$v){
            if(substr($v[1], 0, 1) == '#'||substr($v[1], 0, 5) == 'https'){
                unset($regArr[$k]);
            }
            if(substr($v[1], 0, 2) == './'){
                //$v[1];
            }
            
        }
        print_r($regArr);exit;
        
	for($i=0;$i<count($regArr);$i++){//找出所有匹配的链接

	if(!eregi("://",$regArr[$i][1]))//判断是否是相对路径，即是否还有://

	    if(substr($regArr[$i][1],0,1)=="/")//是否是站点的根目录

	    echo "link".($i+1).":".$site.$regArr[$i][1]."<br/>";//根目录

	    else

	    echo "link".($i+1).":".$base.$regArr[$i][1]."<br/>";//当前目录

	else

	    echo "link".($i+1).":".$regArr[$i][1]."<br/>";//相对路径

	}

	fclose($fp);
    }
  //===================商城接口==========================
    //获取店铺列表
    //type1为月子中心2为试管诊所
    public function get_shop_list(){
        $shop=D("shopBase");
        $type=intval(I("request.type"));
        $shop_class=D("shopClass");
        $state=D("State");
        $country=D("country");
        $res=$shop->where("lid=".$type)->select();
        if(!res){
            $this->echoJson(array('result' => 1, 'info' => "没有此类别"));exit;
        }
        foreach($res as $k=>&$v){
            if($v["is_hz"]==0){
                unset($res[$k]);
                continue;
            }
            unset($v["is_hz"]);
            $r=$shop_class->where("id=".$v['lid'])->find();
            if(!$r){
                $this->echoJson(array('result' => 1, 'info' => "该店铺没有类别"));exit;
            }
            $v['lname']=$r['name'];
            unset($v['lid']);
            $rr=$country->where("countryid=".$v["cid"])->find();
//            echo $country->getLastSql();
            if(!$rr){
                $this->echoJson(array('result' => 1, 'info' => "该店铺没有所属国家"));exit;
            }
            $v['cname']=$rr['countryname_cn'];
            unset($v['cid']);
            if($v['cname']=="美国"){
                $r1=$state->where("id=".$v["zid"])->find();
                if(!$r1){
                    $this->echoJson(array('result' => 1, 'info' => "该店铺没有所属州"));exit;
                }
                $v["zname"]=$r1["name"];
                unset($v["zid"]);
            }
            if($v['logo_img']!=null){
                $v['logo_img']="http://img.other.ivf-bb.com/imageShopLog/".$v['logo_img'];
            }
            if($v["imgs"]!=null){
                $v['imgs']= explode(",",rtrim($v["imgs"], ","));
                foreach($v["imgs"] as &$vv){
                    $vv="http://img.other.ivf-bb.com/imageShop/".$vv;
                }
            }
            
            
        }
        $this->echoJson(array('result' => 0, 'info' => $res));exit;
    }
    //根据店铺id获取店铺下的商品
    //act=0为普通商品其他为活动商品
    public function get_goods_list_by_id($act=0){
        $id=intval(I("request.id"));
        $type=intval(I("request.type"));
        $goods=D("goodsBase");
        $class=D("goodsClass");
        //$stock=D("stock");
        $r=$class->where("id=".$type)->find();
        if(!$r){
            $this->echoJson(array('result' => 1, 'info' => "没有所属商品类别"));exit;
        }
        
        $res=$goods->where("shop_id=".$id." and class_id=".$type." and act_id=".$act)->select();
        if(!$res){
            $this->echoJson(array('result' => 1, 'info' => "没有商品"));exit;
        }
        foreach($res as $k=>&$v){
            //翻译
            if($type==4||$type==5){
                $user=D("User");
                $uu=$user->where("goods like '%".$v['id']."|%'")->find();
                if($uu!=null){
                    $v['userid']=$uu['id'];
                }else{
                    $v['userid']=0;
                }
            }
            $v['class_name']=$r['name'];
            unset($v['class_id']);
            if($v['display_img']!=null){
                $v['display_img']="http://img.other.ivf-bb.com/imageGoodsLog/".$v['display_img'];
            }
            if($v["imgs"]!=''){
                $v['imgs']= explode(",",rtrim($v["imgs"], ","));
                foreach($v["imgs"] as &$vv){
                    $vv="http://img.other.ivf-bb.com/imageGoods/".$vv;
                }
            }
            //库存暂不考虑
//            $rr=$stock->where("goods_id=".$v['id'])->select();
//            $v["stock"]=$rr;
        }
        
        $this->echoJson(array('result' => 0, 'info' => $res));exit;
    }
    //购买时用户信息
    public function goods_user($uid,$type,$cid,$is_order=0){
        $goodsuser=D("GoodsUser");
        $class=D("goodsClass");
        $r1=$class->where("id=".$cid)->find();
        if(!$r1){
            $this->echoJson(array('result' => 1, 'info' => "没有所属商品类别"));exit;
        }
        $r=$goodsuser->where("uid=".$uid." and lid=".$cid." and is_order=".$is_order)->find();
        
        
        if($type==1){
            if(!$r){
                $this->echoJson(array('result' => 1, 'info' => '没有找到'));exit;
            }
            $this->echoJson(array('result' => 0, 'info' => $r));exit;
        }
        if($type==2){
            if(I("request.name")!=''){
                $data['name']=I("request.name");
            }
            if(I("request.en_name")!=''){
                $data['en_name']=I("request.en_name");
            }
            if(I("request.phone")!=''){
                $data['phone']=I("request.phone");
            }
            if(I("request.addr")!=''){
                $data['addr']=I("request.addr");
            }
            if(I("request.garden")!=''){
                $data['garden']=I("request.garden");
            }
            if(I("request.age")!=''){
                $data['age']=I("request.age");
            }
            if(I("request.papers")!=''){
                $data['papers']=I("request.papers");
            }
            if(I("request.papers_type")!=''){
                $data['papers_type']=I("request.papers_type");   
            }
            if(I("request.description")!=''){
                $data['description']=I("request.description");
            }
            
            $data['is_order']=$is_order;
            $data['lid']=$cid;
            
            if(!$r){
                $data['uid']=$uid;
                $rr=$goodsuser->add($data);
                if(!$rr){
                    $this->echoJson(array('result' => 1, 'info' => "添加失败"));exit;
                }
                $this->echoJson(array('result' => 0, 'info' => $rr));exit;
            }
            $rr=$goodsuser->where("uid=".$uid." and lid=".$cid." and is_order=".$is_order)->save($data);
            if(!$rr){
                    $this->echoJson(array('result' => 1, 'info' => "修改失败"));exit;
            }
            $this->echoJson(array('result' => 0, 'info' => "ok"));exit;
        }
    }
    //获取用户的金额
    public function get_money($uid){
        $user=D("User");
        $r=$user->where('id='.$uid)->field("money_available,money_freeze")->find();
        if(!$r){
            $this->echoJson(array('result' => 1, 'info' => '没有找到'));exit;
        }
        $this->echoJson(array('result' => 0, 'info' => $r));exit;
    }
    //商品详情
    public function goods_detail(){
        $goods_id=I("request.goods_id",'');
        $goods=D("goodsBase");
        $class=D("goodsClass");
        $shop=D("shopBase");
        $r=$goods->where("id=".$goods_id)->find();
        if(!$r){
            $this->echoJson(array('result' => 1, 'info' => "error"));exit;
        }
        if($r['display_img']!=null){
                $r['display_img']="http://img.other.ivf-bb.com/imageGoodsLog/".$r['display_img'];
        }
        if($r["imgs"]!=''){
            $r['imgs']= explode(",",rtrim($r["imgs"], ","));
            foreach($r["imgs"] as &$vv){
                $vv="http://img.other.ivf-bb.com/imageGoods/".$vv;
             }
        }
        $r1=$class->where("id=".$r['class_id'])->find();
        if(!$r1){
            $this->echoJson(array('result' => 1, 'info' => "该商品还未添加分类"));exit;
        }
        $r['class_name']=$r1['name'];
        $r2=$shop->where("id=".$r['shop_id'])->find();
        if(!$r2){
            $this->echoJson(array('result' => 1, 'info' => "该商品还未添加所属店铺"));exit;
        }
        $r['shop_name']=$r2['name'];
        $this->echoJson(array('result' => 0, 'info' => $r));exit;
    }
    //加入购物车
//    public function add_user_cart(){
//        $goods_id=intval(I("request.goods_id"));
//        $number=  intval(I("request.num"));
//        $uid=intval(I("request.uid"));
//        $time=intval(I("request.key"));
//        $usercart=D("userCart");
//        $res=$usercart->where("uid=".$uid." and goods_id=".$goods_id." and go_time=".$time)->find();
//        if($number==0){
//            $rr=$usercart->where("uid=".$uid." and goods_id=".$goods_id." and go_time=".$time)->delete();
//            if($rr !== false){
//                $this->echoJson(array('result' => 0, 'info' => "加入成功"));exit;
//            }else{
//                $this->echoJson(array('result' => 1, 'info' => "加入失败"));exit;
//            }
//        }
//        if(!$res){
//            $data['uid']=$uid;
//            $data['goods_id']=$goods_id;
//            $data['num']=$number;
//            $data['go_time']=$time;
//            $data['create_time']=time();
//            $r=$usercart->add($data);
//            if(!$r){
//                $this->echoJson(array('result' => 1, 'info' => "加入失败"));exit;
//            }
//            $this->echoJson(array('result' => 0, 'info' => "加入成功"));exit;
//        }
//        $opt['num']=$number;
//        $opt['go_time']=$time;
//        $opt['update_time']=time();
//        $result = $usercart->where("uid=".$uid." and goods_id=".$goods_id)->save($opt);
//        if(!$result){
//            $this->echoJson(array('result' => 1, 'info' => "加入失败"));exit;
//        }
//        $this->echoJson(array('result' => 0, 'info' => "加入成功"));exit;
//        
//    }
    //获取用户购物车列表
//    public function get_user_cart(){
//        $uid=intval(I("request.uid"));
//        $usercart=D("userCart");
//        $goods=D("goodsBase");
//        $shop=D("shopBase");
//        $res=$usercart->where("uid=".$uid)->select();
//        if(!$res){
//            $this->echoJson(array('result' => 0, 'info' => ""));exit;
//        }
//        $arr=array();
//        foreach($res as $k=>&$v){
//            $r=$goods->where("id=".$v['goods_id'])->find();
//            $arr[$k]['shop_id']=$r['shop_id'];
//            $r1=$shop->where("id=".$r['shop_id'])->find();
//            $arr[$k]['shop_name']=$r1['name'];
//            if($r['display_img']!=null){
//                $v['display_img']="http://".$_SERVER["HTTP_HOST"] . "/tb/imageCareCenter/".$r['display_img'];
//            }
//            $v['shop_id']=$r['shop_id'];
//            $v['abs']=$r['abs'];
//            $v['price']=$r['price'];
//            $v['click']=$r['click'];
//            $v['sale_num']=$r['sale_num'];
//            $v['company']=$r['company'];
//            $v['is_jing']=$r['is_jing'];
//            $v['is_hot']=$r['is_hot'];
//            $v['is_new']=$r['is_new'];
//        }
//        $arr=array_unique($arr);
//        foreach($arr as $kk=>$vv){
//            foreach($res as $vvv){
//                if($vv['shop_id']==$vvv['shop_id']){
//                    $arr[$kk]['shops'][]=$vvv;
//                }
//            }
//            
//        }
//        $this->echoJson(array('result' => 0, 'info' => $arr));exit;
//        //print_r($arr);
//        
//        
//        
//    }
    
    //生成订单
    public function order(){
        $uid=I("request.uid");
        $sig=I("request.sig");
        if(md5($uid."123456")!=$sig){
            $this->echoJson(array('result' => 1, 'info' => "参数错误"));exit;
        }
        $addr_id=I("request.addr_id");
        $shop_id=I("request.shop_id");
        $goods_ids=I("request.goods_ids");
        $goods=D("goodsBase");
        $shopBase=D("shopBase");
        $order=D("orderInfo");
        $GoodsUser=D("GoodsUser");
        $GoodsUser->startTrans();
        $r=$GoodsUser->where("id=".$addr_id.' and is_order=0')->find();
        $class=D("goodsClass");
        $r1=$class->where("id=".$r['lid'])->find();
        if(!$r1){
            $GoodsUser->rollback();
            $this->echoJson(array('result' => 1, 'info' => "没有所属商品类别"));exit;
        }
        $opt['name']=$r['name'];
        $opt['en_name']=$r['en_name'];
        $opt['phone']=$r['phone'];
        $opt['addr']=$r['addr'];
        $opt['garden']=$r['garden'];
        $opt['age']=$r['age'];
        $opt['papers']=$r['papers'];
        $opt['papers_type']=$r['papers_type'];
        $opt['description']=$r['description'];
        $opt['is_order']=1;
        $opt['lid']=$r['lid'];
        $opt['uid']=$uid;
        $ress=$GoodsUser->add($opt);
        
            $order_no=  date("Y",time()).sprintf("%04d", $shop_id).sprintf("%04d", $r['lid']);
            $where['order_no']=array('like',$order_no.'%');
            $rr=$order->where($where)->order("order_no")->limit(1)->order("order_no desc")->find();
            if(!$rr){
                $data['order_no']=$order_no.'000001';
            }else{
                $data['order_no']=$rr['order_no']+1;
            }
            $data['uid']=$uid;
            $data['addr_id']=$ress;
            $data['shop_id']=$shop_id;
            $t=explode(",",rtrim($goods_ids,","));
            $money=0;
            foreach($t as $v){
                $is=$this->is_goods_act($v);
                if($is==-2){
                    $GoodsUser->rollback();
                    $this->echoJson(array('result' => 1, 'info' => "本月活动人数已满,请期待下月^v^"));exit;
                }  elseif ($is==0) {
                    $GoodsUser->rollback();
                    $this->echoJson(array('result' => 1, 'info' => "活动未开始或者已过期"));exit;
                }elseif($is>0){
                    $data['actgoods_id']=$is;
                }
                    
                
                    
                
                $m=$goods->where("id=".$v)->find();
                if(!$m){
                    $GoodsUser->rollback();
                    $this->echoJson(array('result' => 1, 'info' => "没有这个商品"));exit;
                }
                $money+=$m['price'];
            }
            $data['goods_ids']=$goods_ids;
            //判断是否有叶练视频订单,有则减去150美元
            if($shop_id==1&&$r['lid']==2){
                $ret=$order->where('uid='.$uid.' and shop_id=1 and lid=3 and svol_id=1')->limit(1)->find();
                if($ret!=null){
                    if(!$order->where('uid='.$uid.' and shop_id=1 and lid=2 and svol_id=2')->limit(1)->find()){
                        $data['svol_id']=2;
                        $money-=150;
                    }
                    
                }
            }
            if($shop_id==1&&$r['lid']==3){
                $data['svol_id']=1;
            }
            
            $data['goods_total_price']=$money;
            $rrr=$shopBase->where("id=".$shop_id)->find();
            //获取汇率
            $rate=D("Rate");
            $r1=$rate->where("to_bz='CNY' and from_bz='".$rrr['bz']."'")->find();
            if($rrr['bz']=='CNY'){
                $data['rate']=1;
            }else{
                $data['rate']=$r1['rate_val'];
            }
            $data['cn_goods_total_money']=$this->getExchangeRate($money,0,$rrr['bz'],"CNY")->retData->convertedamount;
            $user=D("User");
            $r1=$user->where('id='.$uid)->field("money_available,money_freeze")->find();
            if(!$r1){
                $this->echoJson(array('result' => 1, 'info' => '没有找到该用户'));exit;
            }
            
            //视频服务判断
            if($r['lid']==3){
                $Doctor=D("Doctor");
                $dd=$Doctor->where("goods_id=".rtrim($goods_ids,","))->find();
                $data['doctor_id']=$dd['id'];
            }else{
                $data['doctor_id']=0;
            }
            $data['lid']=$r['lid'];
            $data['order_status']=0;
            $data['pay_status']=1;
            $data['user_status']=0;
            $data['create_time']=time();
            $mmm=floatval($r1['money_available'])-floatval($data['cn_goods_total_money']);
            if($mmm<0){
                $data['pay_status']=0;
            }
            $res=$order->add($data);
            
            if(!$res){
                $GoodsUser->rollback();
                $this->echoJson(array('result' => 1, 'info' => "生成订单失败"));exit;
            }
            
            if($mmm<0){
                $GoodsUser->commit();
                $this->echoJson(array('result' => 2, 'info' => $res));exit;
            }
            
            
            $user->where('id='.$uid)->save(array("money_available"=>$mmm));
            $log=D("OrderLog");
            $logs['money']=$data['cn_goods_total_money'];
            $logs['log']="用户id为".$uid."购买了商品id为".$goods_ids."当前的汇率为".$data['rate'];
            $logs['create_time']=$data['create_time'];
            $log->add($logs);
            $GoodsUser->commit();
            $this->echoJson(array('result' => 0, 'info' => "支付成功"));exit;
    }
    //判断是否有叶练视频订单,有则减去150美元
    public function is_yelian($shop_id,$uid){
            if($shop_id==1){
                $order=D('OrderInfo');
                $ret=$order->where('uid='.$uid.' and shop_id=1 and lid=3 and svol_id=1')->limit(1)->find();
                if($ret!=null){
                    if($order->where('uid='.$uid.' and shop_id=1 and lid=2 and svol_id=2')->limit(1)->find()){
                        $this->echoJson(array('result' => 0, 'info' => 0));exit;
                    }
                    $this->echoJson(array('result' => 0, 'info' => 150));exit;
                }else{
                    $this->echoJson(array('result' => 0, 'info' => 0));exit;
                }
            }else{
                $this->echoJson(array('result' => 0, 'info' => 0));exit;
            }
    }
    
    //根据商品id查询是否是活动id并且是否能成为订单
    private function is_goods_act($id){
        $goods=D("goodsBase");
        $GoodsActivity=D("GoodsActivity");
        $order=D("orderInfo");
        $m=$goods->where("id=".$id." and act_id!=0")->find();
        if(!$m){
            return -1;//不是活动
        }
        $re=$GoodsActivity->where("id=".$m['act_id'])->find();
        //判断活动时间是否过期
        if(time()<$re['start_time']||time()>$re['end_time']){
            return 0;//活动未开始或者已过期
        }
        
        
        if($re['type']==3){
            $firstday = date("Y-m-01",time());
            $lastday = date("Y-m-d",strtotime("$firstday +1 month -1 day"));
            $f=strtotime($firstday);
            $l=strtotime($lastday);
            $where="create_time >$f and create_time<$l and actgoods_id=".$m['act_id'];
            $num=$order->where($where)->count();
            if($num<$re['limit_number']){
                return $m['act_id'];
            }else{
                return -2;//本月人数已满
            }
        }
        
        
        
        
    }
    
    //获取汇率
    public function getExchangeRate($money,$type='0',$from='USD',$to='CNY'){
//        $ch = curl_init();
//        $url = 'http://apis.baidu.com/apistore/currencyservice/currency?fromCurrency='.$form.'&toCurrency='.$to.'&amount='.$money;
//            $header = array(
//                'apikey:eac07dc202125ba68e54d0c8a18a8e40',
//            );
//            // 添加apikey到header
//            curl_setopt($ch, CURLOPT_HTTPHEADER  , $header);
//            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//            // 执行HTTP请求
//            curl_setopt($ch , CURLOPT_URL , $url);
//            $res = curl_exec($ch);
        $obj=new \stdClass();
        $obj->errNum=0;
        $obj->errMsg="success";
        $data=new \stdClass();
        $data->fromCurrency=$from;
        $data->toCurrency=$to;
        $rate=D("Rate");
        $r1=$rate->where("from_bz='".$from."' and to_bz='".$to."'")->find();
        $data->amount=$money;
        if($from==$to){
            $data->currency=1;
            $data->convertedamount=$money;
            
        }else{
            $data->currency=$r1['rate_val'];
            $data->convertedamount=$money*$r1['rate_val'];
        }
        $obj->retData=$data;
            
            if($type==1){
                echo json_encode($obj);exit;
            }
            return $obj;
    }

    //获取用户订单列表
    public function order_by_id(){
        $uid=I("request.uid");
        $sig=I("request.sig");
        if(md5($uid."123456")!=$sig){
            $this->echoJson(array('result' => 1, 'info' => "参数错误"));exit;
        }
        $user=D("User");
        $u=$user->where('id='.$uid)->find();
        if(!$u){
            $this->echoJson(array('result' => 1, 'info' => "没有该用户"));exit;
        }
        if($u['goods']!=0){
            $a=explode("|",rtrim($u['goods'],"|"));
            foreach($a as &$s){
                $s=$s.',';
            }
            if(count($a)==2){
                $map="goods_ids='$a[0]' OR goods_ids='$a[1]'";
            }elseif(count($a)==1){
                $map="goods_ids='$a[0]'";
            }
            
        }else{
            $map="uid=".$uid;
        }
        $order=D("OrderInfo");
        $goods=D("GoodsBase");
        $GoodsUser=D("GoodsUser");
        $shop=D("shopBase");
        $res=$order->where($map)->order("create_time desc")->select();
//        echo $order->getLastSql();exit;
        if(!$res){
            $this->echoJson(array('result' => 1, 'info' => "没有该订单"));exit;
        }
        $arr=array();
        foreach($res as $k=>$v){
            $arr[$k]['oid']=$v['id'];
            $opt=$shop->where("id=".$v['shop_id'])->find();
            $arr[$k]['shop_id']=$v['shop_id'];
            $arr[$k]['shop_name']=$opt['name'];
            $arr[$k]['shop_en_name']=$opt['en_name'];
            $arr[$k]['shop_class']=$opt['lid'];
            $arr[$k]['no']=$v['order_no'];
            $t=explode(',',rtrim($v['goods_ids'],','));
            foreach($t as $vv){
                $r1=$goods->where('id='.$vv)->field("name,en_name,abstract,en_abstract,maternity_matron,en_maternity_matron")->find();
                if($r1['abstract']!=null&&$r1['maternity_matron']!=null){
                    $r1['abstract']=$r1['abstract']."\n\n".$r1['maternity_matron'];
                }
                if($r1['en_abstract']!=null&&$r1['en_maternity_matron']!=null){
                    $r1['en_abstract']=$r1['en_abstract']."\n\n".$r1['en_maternity_matron'];
                }
                $arr[$k]['goods'][]= $r1;
            }
            if($opt['imgs']!=null){ 
                $temp=explode(',',rtrim($opt['imgs'],","));
                foreach($temp as &$vvv){
                    $vvv="http://img.other.ivf-bb.com/imageShop/".$vvv;
                }
                $arr[$k]['shop_img']=$temp;
            }else{
                $arr[$k]['shop_img']='';
            }
            $arr[$k]['create_time']=$v['create_time'];
            $arr[$k]['total_price']=$v['cn_goods_total_money'];
            $r=$GoodsUser->where("id=".$v['addr_id'])->find();
            if(!$r){
                $this->echoJson(array('result' => 1, 'info' => "订单错误"));exit;
            }
            $arr[$k]['addr']=$r;
            $arr[$k]['optimum_time']=$v['optimum_time'];
            $arr[$k]['end_time']=$v['end_time'];
            //返回这个方便视频判断
            $arr[$k]['doctor_id']=$v['doctor_id'];
            if($v['pay_status']==0&&$v['order_status']==0){
                $arr[$k]['status']="未付款";
            }elseif($v['pay_status']==1&&$v['order_status']==0){
                $arr[$k]['status']="已支付";
            }elseif($v['pay_status']==1&&$v['order_status']==1){
                $arr[$k]['status']="已确定";
            }elseif($v['pay_status']==1&&$v['order_status']==2){
                $arr[$k]['status']="已取消";
            }elseif($v['pay_status']==1&&$v['order_status']==3){
                $arr[$k]['status']="已关闭";
            } 
        }
        $this->echoJson(array('result' => 0, 'info' => $arr));exit;

    }
    
    
    //判断用户是否绑卡
    public function is_bind_cart(){
        $uid=I("request.uid");
        $user=D("User");
        $r=$user->where("id=".$uid)->find();
        if(!$r){
            $this->echoJson(array('result' => 1, 'info' => "没有此用户"));exit;
        }
        $UserBigMoney=D("UserBigmoney");
        $res=$UserBigMoney->where("uid=".$uid." and is_status=1")->find();
        if(!$res){
            $this->echoJson(array('result' => 0, 'info' => 0));exit;
        }
        $this->echoJson(array('result' => 0, 'info' => 1));exit;
    }
    
    //收藏接口
//    public function shop_sc(){
//        $is_sc=I("request.is_sc","");
//        $goods_id=I("request.goods_id","");
//        $uid=I("request.uid","");
//        $goodsSc=D("goodsSc");
//        $res=$goodsSc->where("uid=".$uid." and goods_id=".$goods_id)->find();
//        if(!$res&&$is_sc==1){
//            $data['uid']=$uid;
//            $data['goods_id']=$goods_id;
//            $data['is_sc']=1;
//            $goodsSc->add($data);
//            $this->echoJson(array('result' => 1, 'info' => "ok"));exit;
//        }elseif(isset($res)){
//            $r=$goodsSc->where("uid=".$uid." and goods_id=".$goods_id)->setField("is_sc",$is_sc);
//            if(!$r){
//                $this->echoJson(array('result' => 0, 'info' => "error"));exit;
//            }
//            $this->echoJson(array('result' => 1, 'info' => "ok"));exit;
//        }
//        $this->echoJson(array('result' => 0, 'info' => "error"));exit;
//    }
    //我的收藏列表
//    public function my_sc(){
//        $uid=I("request.uid","");
//        $goodsSc=D("goodsSc");
//        $goods=D("goodsBase");
//        $goodsClass=D("goodsClass");
//        $res=$goodsSc->where("uid=".$uid)->select();
//        if(!$res){
//            $this->echoJson(array('result' => 1, 'info' => ""));exit;
//        }
//        $arr=array();
//        foreach($res as $k=>$v){
//            $r=$goods->where("id=".$v['goods_id'])->find();
//            if(!$r){
//                $this->echoJson(array('result' => 0, 'info' => "error"));exit;
//            }
//            $arr[]=$r;
//        }
//        $this->echoJson(array('result' => 1, 'info' => $r));exit;
//    }
    //获取商品的评论列表
//    public function goods_comment_list(){
//        $goods_id=I("request.goods_id",'');
//        $goodsComment=D("goodsComment");
//        $goodsCommentImgs=D("goodsCommentImgs");
//        $goods=D("goodsBase");
//        $r=$goodsComment->where("goods_id=".$goods_id)->select();
//        foreach($r as &$v){
//            $res=$goodsCommentImgs->where("uid=".$v['uid']." and goods_id=".$v['goods_id']." and create_time=".$v['create_time'])->find();
//            if($res["imgs"]!=''){
//                $arr= explode(",",rtrim($r["imgs"], ","));
//                foreach($arr as &$vv){
//                    $vv="http://".$_SERVER["HTTP_HOST"] . "/tb/imageGoods/".$vv;
//                }
//                $v['imgs']==$arr;
//            }else{
//                $v['imgs']='';   
//            }
//            $rr=$goods->where('id='.$goods_id)->find();
//            $v['goods_name']=$rr['name'];
//        }
//    }

    
/***********************每日记录接口*************************/
    //添加用户月经参数
    //type1为添加 2为修改 3为查询
    public function yuejing(){
        $type=intval(I("request.type"));
        $uid=intval(I("request.uid"));
        $user_menstruation=D("UserMenstruation");
        if($type==3){
            $r=$user_menstruation->where('uid='.$uid)->find();
            if(!$r){
                $this->echoJson(array('result' => 1, 'info' => "没有信息"));exit;
            }
            $this->echoJson(array('result' => 0, 'info' => $r));exit;
        }
        $data['menstruation_time']=I("request.menstruation_time",'');
        $data['menstruation_cycle']=I("request.menstruation_cycle",'');
        $data['menstruation_last']=I("request.menstruation_last",'');
        if($type==1){
            $data['uid']=$uid;
            $rr=$user_menstruation->where('uid='.$uid)->find();
            if($rr!=null){
                $this->echoJson(array('result' => 1, 'info' => "已经有该用户信息,无法添加"));exit;
            }
            $r=$user_menstruation->add($data);
            if(!$r){
                $this->echoJson(array('result' => 1, 'info' => "添加失败"));exit;
            }
            $this->echoJson(array('result' => 0, 'info' => 'ok'));exit;
        }elseif($type==2){
            $id=intval(I("request.id"));
            $r=$user_menstruation->where('id='.$id)->save($data);
            if(!$r){
                $this->echoJson(array('result' => 1, 'info' => "修改失败"));exit;
            }
            $this->echoJson(array('result' => 0, 'info' => 'ok'));exit;
        }
    }
    //添加或者修改每日记录
    //type1为添加 2为修改 3为查询
    public function daily_basis(){
        $type=intval(I("request.type"));
        $uid=  intval(I("request.uid"));
        $times=I("request.times",'');
        $DailyBasis=D("DailyBasis");
        if($type==3){
            $r=$DailyBasis->where('uid='.$uid.' and times="'.$times.'"')->find();
            if(!$r){
                $this->echoJson(array('result' => 1, 'info' => "没有信息"));exit;
            }
           
//            if($r['symptom']!=null){
//                $r['symptom']=explode(",",rtrim($r["symptom"], ","));
//            }
            $this->echoJson(array('result' => 0, 'info' => $r));exit;
        }
        
        if($type==1){
            if(I("request.is_dym")!=''){
                $data['is_dym']=I("request.is_dym");
            }
            if(I("request.color")!=''){
                $data['color']=I("request.color");
            }
            if(I("request.flow")!=''){
                $data['flow']=I("request.flow");
            }
            if(I("request.dysmenorrhea")!=''){
                $data['dysmenorrhea']=I("request.dysmenorrhea");
            }
            if(I("request.clot")!=''){
                $data['clot']=I("request.clot");
            }
            if(I("request.from_bed")!=''){
                $data['from_bed']=I("request.from_bed");
            }
            if(I("request.bbt")!=''){
                $data['bbt']=I("request.bbt");
            }
            if(I("request.leucorrhea")!=''){
                $data['leucorrhea']=I("request.leucorrhea");
            }
            if(I("request.symptom")!=''){
                $data['symptom']=I("request.symptom");
            }
            if(I("request.pregnant_diary")!=''){
                $data['pregnant_diary']=I("request.pregnant_diary");
            }
            $data['times']=$times;
            $data['uid']=$uid;
            $r=$DailyBasis->where('uid='.$uid.' and times="'.$times.'"')->find();
            if(!$r){
                $rr=$DailyBasis->add($data);
                if(!$rr){
                    $this->echoJson(array('result' => 1, 'info' => "添加失败"));exit;
                }
                $this->echoJson(array('result' => 0, 'info' => 'ok'));exit;
            }
            $rrr=$DailyBasis->where('id='.$r['id'])->save($data);
            if(!$rrr){
                $this->echoJson(array('result' => 1, 'info' => "修改失败"));exit;
            }
            $this->echoJson(array('result' => 0, 'info' => 'ok'));exit;
        }
    }
    //添加试纸
    //type1为添加 2为修改 3为查询 4为删除
    public function shizhi(){
        $type=intval(I("request.type"));
        $uid=  intval(I("request.uid"));
        $opt=  intval(I("request.opt"));
        $Paper=D("Paper");
        if($type==3){
            $go_time=I("request.go_time");
            $to_time=I("request.to_time");
            $res=$Paper->where("times>".$go_time." and times<".$to_time." and uid=".$uid." and opt=".$opt)->select();
            if(!$res){
                $this->echoJson(array('result' => 1, 'info' => "查询失败"));exit;
            }
            foreach($res as &$v){
                $v['img']="http://img.other.ivf-bb.com/imagesz/".$v['img'];
            }
            $this->echoJson(array('result' => 0, 'info' => $res));exit;
        }
        if($type==2){
            $id=intval(I("request.id"));
            $data['times']=I("request.times",'');
            $data['results']=I("request.results",'');
            $r=$Paper->where('uid='.$uid." and opt=".$opt." and id=".$id)->save($data);
            if(!$r){
                $this->echoJson(array('result' => 1, 'info' => "修改失败"));exit;
            }
            $this->echoJson(array('result' => 0, 'info' => 'ok'));exit;
        }
        if($type==1){
            if($_FILES['img']['name']!=null){
                
                $setting=C('UPLOAD_SITEIMG_QINIU');
                $setting['driverConfig']['domain']='img.other.ivf-bb.com';
                $setting['driverConfig']['bucket'] = 'other';
//                $setting['saveName'] = array ('uniqid', 'imagesz_');
                $setting['subName'] = 'imagesz/'.date('Y-m-d',time());
                $Upload = new \Think\Upload($setting);
                $info = $Upload->upload($_FILES);
                 $t=  date('Y-m-d',time());
                 $name=$t.'/'.$info['img']['savename'];
                if(!$info){
                    $data['img']='';
                }else{
                    $data['img']=  $name;
                }
            }else{
                $this->echoJson(array('result' => 1, 'info' => "没有图片"));exit;
            }
            $data['times']=I("request.times",'');
            $data['results']=I("request.results",'');
            $data['uid']=$uid;
            $data['opt']=$opt;
            $r=$Paper->add($data);
            if(!$r){
                $this->echoJson(array('result' => 1, 'info' => "添加失败"));exit;
            }
            $this->echoJson(array('result' => 0, 'info' => 'ok'));exit;
        }
        if($type==4){
            $id=intval(I("request.id"));
            $res=$Paper->where("id=".$id)->find();
            if(!$res){
                $this->echoJson(array('result' => 1, 'info' => "没有此id"));exit;
            }
            unlink("./imagesz/".$r['logo_img']);
            $r=$Paper->where("id=".$id)->delete();
            if(!$r){
                $this->echoJson(array('result' => 1, 'info' => "删除失败"));exit;
            }
            $this->echoJson(array('result' => 0, 'info' => 'ok'));exit;
        }
    }
    
    //php获取中文字符拼音首字母
    function getFirstCharter($str=''){
        if($str=="重庆"){return 'C';};
        if(empty($str)){return '';}
        $fchar=ord($str{0});
        if($fchar>=ord('A')&&$fchar<=ord('z')) return strtoupper($str{0});
        $s1=iconv('UTF-8','gb2312',$str);
        $s2=iconv('gb2312','UTF-8',$s1);
        $s=$s2==$str?$s1:$str;
        $asc=ord($s{0})*256+ord($s{1})-65536;
       if($asc>=-20319&&$asc<=-20284) return 'A';
       if($asc>=-20283&&$asc<=-19776) return 'B';
       if($asc>=-19775&&$asc<=-19219) return 'C';
       if($asc>=-19218&&$asc<=-18711) return 'D';
       if($asc>=-18710&&$asc<=-18527) return 'E';
       if($asc>=-18526&&$asc<=-18240) return 'F';
       if($asc>=-18239&&$asc<=-17923) return 'G';
       if($asc>=-17922&&$asc<=-17418) return 'H';
       if($asc>=-17417&&$asc<=-16475) return 'J';
       if($asc>=-16474&&$asc<=-16213) return 'K';
       if($asc>=-16212&&$asc<=-15641) return 'L';
       if($asc>=-15640&&$asc<=-15166) return 'M';
       if($asc>=-15165&&$asc<=-14923) return 'N';
       if($asc>=-14922&&$asc<=-14915) return 'O';
       if($asc>=-14914&&$asc<=-14631) return 'P';
       if($asc>=-14630&&$asc<=-14150) return 'Q';
       if($asc>=-14149&&$asc<=-14091) return 'R';
       if($asc>=-14090&&$asc<=-13319) return 'S';
       if($asc>=-13318&&$asc<=-12839) return 'T';
       if($asc>=-12838&&$asc<=-12557) return 'W';
       if($asc>=-12556&&$asc<=-11848) return 'X';
       if($asc>=-11847&&$asc<=-11056) return 'Y';
       if($asc>=-11055&&$asc<=-10247) return 'Z';
       return null;
    }
    ///////////////////139容联接口////////////////////////
    //根据用户id获取容联账号信息
    public function get_rl_by_id(){
        $uid=intval(I("request.uid"));
        $rl=D("Rl");
        $r=$rl->where("uid=".$uid)->find();
        if(!$r){
            $this->echoJson(array('result' => 1, 'info' => "没有数据"));exit;
        }
        $this->echoJson(array('result' => 0, 'info' => $r));exit;
    }
//   public function aaa($function_name,$opt1,$opt2){
//       $this->$function_name($opt1,$opt2);
//   }
    //////////////////////祈贝通讯/////////////////////////
    public function qbreg(){
            $rl=D("TestRl");
            $user=I("request.username");
            $pwd=I("request.password");
            $pwd=md5($pwd);
            $r=$rl->where("username='".$user."'")->find();
            if($r!=null){
                $this->echoJson(array('result' => 1, 'info' => '该用户已经注册过'));exit;
            }
                $REST=new \Org\Util\REST($this->serverIP,$this->serverPort,$this->softVersion);
                $REST->setAccount($this->accountSid,$this->accountToken);
                $REST->setAppId($this->appId);
                $result = $REST->CreateSubAccount('ivf'.$user);
                if($result == NULL ) {
                    $this->echoJson(array('result' => 10, 'reason' => '创建容联失败'));
                    exit;
                }
                if($result->statusCode!=0) {
                    $this->echoJson(array('result' => 10, 'reason' => '创建容联失败'));exit;
                }else {
                    // 获取返回信息
                    $result=json_decode(json_encode($result),TRUE);
                    $subaccount = $result['SubAccount'];
                    $subAccountid=$subaccount['subAccountSid'];
                    $subToken=$subaccount['subToken'];
                    $dateCreated=$subaccount['dateCreated'];
                    $voipAccount=$subaccount['voipAccount'];
                    $voipPwd=$subaccount['voipPwd'];
                    $data['subAccountid']=$subAccountid;
                    $data['subToken']=$subToken;
                    $data['dateCreated']=$dateCreated;
                    $data['voipAccount']=$voipAccount;
                    $data['voipPwd']=$voipPwd;
                    $data['username']=$user;
                    $data['password']=$pwd;
                    $data['name']='ivf'.$user;
                    $rl->add($data);
                    
                    $this->echoJson(array('result' => 0, 'info' => '注册成功'));exit;
                } 
    }
    public function qblogin(){
        $user=I("request.username");
        $pwd=I("request.password");
        $pwd=md5($pwd);
        $rl=D("TestRl");
        $r=$rl->where("username='".$user."' and password='".$pwd."'")->find();
            if(!$r){
                $this->echoJson(array('result' => 1, 'info' => '没有此用户'));exit;
            }
        $this->echoJson(array('result' => 0, 'info' => $r));exit;    
    }
    public function get_rl_id(){
        $voipAccount=intval(I("request.voipAccount"));
        $username=I("request.username");
        $rl=D("TestRl");
        if($username!=null){
            $r=$rl->where("username='".$username."'")->find();
        }else{
            $r=$rl->where("voipAccount='".$voipAccount."'")->find();
        }
        if(!$r){
            $this->echoJson(array('result' => 1, 'info' => "没有数据"));exit;
        }
        $this->echoJson(array('result' => 0, 'info' => $r));exit;
    }
    public function get_rl_list(){
        $rl=D("TestRl");
        $r=$rl->select();
        if(!$r){
            $this->echoJson(array('result' => 1, 'info' => "没有数据"));exit;
        }
        $this->echoJson(array('result' => 0, 'info' => $r));exit;
    }
    /////////////////////////患者版版本更新///////////////////////
    public function qbversion($no=''){
        if($no=='2.5.0'){
            $this->echoJson(array('result' => 1, 'info' => "no"));exit;
        }
        if($this->qibeiversion[count($this->qibeiversion)-1]!=$no){
            $this->echoJson(array('result' => 0, 'info' => "有新版本了!",'is'=>1));exit;
        }
        $this->echoJson(array('result' => 1, 'info' => "no"));exit;
    }
    /////////////////////////医生版版本更新///////////////////////
    public function doctorqbversion($no=''){
        if($no=='2.5.0'){
            $this->echoJson(array('result' => 1, 'info' => "no"));exit;
        }
        if($this->doctorqibeiversion[count($this->doctorqibeiversion)-1]!=$no){
            $this->echoJson(array('result' => 0, 'info' => "有新版本了!",'is'=>1));exit;
        }
        $this->echoJson(array('result' => 1, 'info' => "no"));exit;
    }
    
    //生成token
    function create_unique() {    
        $data = $_SERVER['HTTP_USER_AGENT'] . $_SERVER['REMOTE_ADDR'].time() . rand();    
        echo sha1($data);    
        //return md5(time().$data);    
        //return $data;    
    }
    
    ////////////////////////////支付/////////////////////////
//    //获取银行卡列表
//    public function get_bankcard_list(){
//        $bandcard_class=D("BandcardClass");
//        $res=$bandcard_class->select();
//        if(!$res){
//            $this->echoJson(array('result' => 1, 'info' => "空"));exit;
//        }
//        foreach($res as &$v){
//            if($v['logo']!=null){
//                $v['logo']='http://'.$_SERVER["HTTP_HOST"] . "/tb/Public/imageBankcard/".$v['logo'];
//            }
//        }
//        $this->echoJson(array('result' => 0, 'info' => $res));exit;
//    }
    //获取指定用户绑定的银行卡列表和银行卡列表
    public function get_bankcard_list_by_uid(){
        $uid=I("request.uid");
        $bandcard_class=D("BandcardClass");
        $user_bigmoney=D("UserBigmoney");
        $bigmoney_yhk=D("BigmoneyYhk");
        $res=$user_bigmoney->where("uid=".$uid." and is_status=1")->select();
        if($res!=null){
            $arr=array();
            foreach($res as $k=>$v){
                $r=$bigmoney_yhk->where("id=".$v['big_id'])->find();
                if(!$r){
                    $this->echoJson(array('result' => 1, 'info' => "error"));exit;
                }
                $arr[$k]['ubig_id']= $v['big_id'];
                $arr[$k]['no_end']=  substr($r['cart_no'], -4);
                $rr=$bandcard_class->where("id=".$r['cart_class_id'])->find();
                if(!$rr){
                    $this->echoJson(array('result' => 1, 'info' => "error"));exit;
                }
                if($rr['logo']!=null){
                    $rr['logo']="http://img.other.ivf-bb.com/imageBankcard/".$rr['logo'];
                }

                $arr[$k]['logo']= $rr['logo'];
                $arr[$k]['name']= $rr['name'];
            }
        }
        $result=$bandcard_class->order("orders desc")->select();
        if(!$result){
            $this->echoJson(array('result' => 1, 'info' => "空"));exit;
        }
        foreach($result as &$vv){
            if($vv['logo']!=null){
                $vv['logo']="http://img.other.ivf-bb.com/imageBankcard/".$vv['logo'];
            }
        }
        $this->echoJson(array('result' => 0, 'info' => $arr,'list'=>$result));exit;
    }
    
    //获取验证码
    public function getyzm(){
                $ubig_id=I("request.ubig_id");
                $phone=I("request.phone");
                $money=I("request.money");
                $end=I("request.end");
                $name=I("request.name");
                $sig=I("request.sig");
                if($sig!=md5($end."qb123")){
                    $this->echoJson(array('result' => 1, 'info' => "逗比!"));exit;
                }
                if($ubig_id!=''){
                    $bigmoney_yhk=D("BigmoneyYhk");
                    $r=$bigmoney_yhk->where("id=".$ubig_id." and is_status=1")->find();
                    if(!$r){
                        $this->echoJson(array('result' => 1, 'info' => '参数错误'));exit;
                    }
                    $phone=$r['phone'];
                }
                //扣款短信
                $username = '70212023'; 
		$password = '7dcae6b06b8f784611dea71afe50707e';
                $yzm=rand(100000, 999999);
                if(!preg_match('/^1[3|4|5|8][0-9]\d{4,8}$/',$phone)){ //匹配
                    $this->echoJson(array('result' => 1, 'info' => "手机号格式错误"));exit;
                }
                $content="请勿告诉任何人!您尾号".$end."正在呱呱试管委托扣款:".$money."元，验证码:".$yzm."。";
		$http = 'http://api.duanxin.cm/?action=send&username='.$username.'&password='.$password.'&phone='.$phone.'&content='.urlencode( iconv('utf-8','gbk',$content) );
		$ch=curl_init();
		curl_setopt($ch,CURLOPT_URL,$http);
		curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
		$data = curl_exec($ch);
		curl_close($ch);
                
                //sesseion 对app端不管用只好使用数据库了
                        $temp_info = D('temp_info'); 			
			$datas['uid'] = $phone;
			$datas['attach'] = $yzm;
			$datas['time'] =  date('Y-m-d',time());
			$datas['expire_time'] = time()+75;//300秒失效,短信接口比较慢，时间放长一点。
			$temp_info->add($datas);	
//                session(array($this->num2str($phone)=>$yzm,'expire'=>3600));
		$this->echoJson(array('result' => 0, 'info' => $data));
    }
    public function testipe(){
        $phone=I("request.phone");
        $username='70211594';
        $password='f307f407a99db037a1541701481a0208';
        $content="请勿告诉任何人!您尾号1234正在呱呱试管委托扣款:1000元，验证码:123。";
		$http = 'http://api.duanxin.cm/?action=send&username='.$username.'&password='.$password.'&phone='.$phone.'&content='.urlencode( iconv('utf-8','gbk',$content) );
		$ch=curl_init();
		curl_setopt($ch,CURLOPT_URL,$http);
		curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
		$data = curl_exec($ch);
		curl_close($ch);
		$this->echoJson(array('result' => 0, 'info' => $data));
    }
    private function num2str($str){
            $new = '';
            $t="qwertyuiop";
            $t=  str_split($t);
            $str= str_split($str);
            for ($i=0; $i<  count($str); $i++) {
                $temp=  intval($str[$i]);
                $new .= $t[$temp];
            }
            return $new;
    }
    
    //type1类id 2ubig_id
    //获取订单表id到支付
    //中转方法
    public function transfer(){
        
        $type=I("request.type");
        $typeid=I("request.typeid");
        $order_id=I("request.oid");
        $uid=I("request.uid");
        $money=I("request.money");
        $yzm=I("request.yzm");
        $sig=I("request.sig");
        if($sig!=md5($uid."qb123")){
            $this->echoJson(array('result' => 1, 'info' => "逗比!"));exit;
        }
        
        $phone=I("request.phone");
        $cart_no=I("request.cart_no");
        $cart_name=I("request.cart_name");
        $cart_sfz=I("request.cart_sfz");
        $money=  sprintf("%0.2f",$money);
        if($order_id!=0){
            $OrderInfo=D("OrderInfo");
            $res=$OrderInfo->where("id=".$order_id)->find();
            if(!$res){
                $this->echoJson(array('result' => 1, 'info' => '订单错误'));exit;
            }
            if($res['cn_goods_total_money']!=$money){
                $this->echoJson(array('result' => 1, 'info' => '金额不匹配'));exit;
            }
        }
        if($type==1){
            $temp_info = D('temp_info');
            $re=$temp_info->where("uid=".$phone)->order("expire_time desc")->limit(1)->find();
            if(!$re){
                $this->echoJson(array('result' => 1, 'info' => '没有该手机号'));exit;
            }
            
            if($yzm!=$re['attach']){
                $this->echoJson(array('result' => 1, 'info' => '验证码错误'));exit;
            }
            if($re['expire_time']<time()){
                $this->echoJson(array('result' => 1, 'info' => '验证码已过期'));exit;
            }
            $this->bind_cart($uid,$money,$cart_no,$cart_name,$cart_sfz,$phone,$typeid,$order_id);
        }else if($type==2){
            $user_bigmoney=D("UserBigmoney");
            $r=$user_bigmoney->where("id=".$typeid." and is_status=1")->find();
            if(!$r){
                $this->echoJson(array('result' => 1, 'info' => '没有用户绑定信息'));exit;
            }
            $bigmoney_yhk=D("BigmoneyYhk");
            $rr=$bigmoney_yhk->where("id=".$r['big_id']." and is_status=1")->find();
            if(!$rr){
                $this->echoJson(array('result' => 1, 'info' => '没有银行卡信息'));exit;
            }
            
            $arr=explode('|',$_SESSION[$this->num2str($rr['phone'])]);
            if($arr[0]==$yzm){
                $this->echoJson(array('result' => 1, 'info' => '验证码错误'));exit;
            }
            if($arr[1]>time()){
                $this->echoJson(array('result' => 1, 'info' => '验证码已过期'));exit;
            }
            $_SESSION[$this->num2str($rr['phone'])]=null;
            $this->bind_cart($uid,$money,$rr['cart_no'],$rr['cart_name'],$rr['cart_sfz'],$rr['phone'],$rr['cart_class_id'],$order_id);
        }
    }
    
    
    //用户绑卡
    //$uid用户id
    //$money
    //$hanghao行号
    //$cart_no银行卡号
    //$cart_name姓名
    //$cart_sfz身份证
    //$phone手机号
    //$class_id银行卡种类id
    private function bind_cart($uid,$money,$cart_no,$cart_name,$cart_sfz,$phone,$class_id,$order_id=0){
//        $uid=I("request.uid");
//        $money=I("request.money");
//        $cart_no=I("request.cart_no");
//        $cart_name=I("request.cart_name");
//        $cart_sfz=I("request.cart_sfz");
//        $phone=I("request.phone");
        $user=D("User");
        $r=$user->where("id=".$uid)->find();
        if(!$r){
            $this->echoJson(array('result' => 1, 'info' => "没有此用户"));exit;
        }
        //判断银行卡种类
        $bandcard_class=D("BandcardClass");
        $rrr=$bandcard_class->where("id=".$class_id)->find();
        if(!$rrr){
            $this->echoJson(array('result' => 1, 'info' => "没有此用户"));exit;
        }
        //此处还应该校验4元素(老板说不加)
        $money=sprintf("%0.2f",$money);
        if($money<=0){
            $this->echoJson(array('result' => 1, 'info' => "金额有误"));exit;
        }
        $bigmoney_yhk=D("BigmoneyYhk");
        $rrrr=$bigmoney_yhk->where("cart_no='".$cart_no."' and is_status=1")->find();
        
        $UserBigMoney=D("UserBigmoney");
        $res=$UserBigMoney->where("uid=".$uid." and is_status=1")->find();
        if(!$res||!$rrrr){
            $result=$bigmoney_yhk->where("cart_no='".$cart_no."' and is_status=1")->find();
            if(!$result){
                $data['cart_no']=$cart_no;
                $data['cart_name']=$cart_name;
                $data['cart_sfz']=$cart_sfz;
                $data['phone']=$phone;
                $data['cart_class_id']=$class_id;
                $data['create_time']=time();
                $big_id=$bigmoney_yhk->add($data);
                $opt['big_id']=$big_id;
            }else{
                $opt['big_id']=$result['id'];
            }
            $opt['uid']=$uid;
            $opt['create_time']=time();
            $UserBigMoney->add($opt);
            $big_ids=$opt['big_id'];
        }else{
            $big_ids=$res['big_id'];
        }
        $recharge_order=D("RechargeOrder");
        $ymd=  date("Ymd",time());
        $r1=$recharge_order->where("date_ymd=".$ymd)->order("id desc")->limit(0,1)->find();
        if(!$r1){
            $packetno_end='00001';
        }else{
            $packetno_end=  sprintf("%05d",$r1['packetno_end']+1);
        }
//        print_r($packetno_end."<br/>".$cart_no."<br/>".$cart_name."<br/>".$money);
        $is=$this->big_money($packetno_end,$rrr['hanghao'],$cart_no,$cart_name,$money);
        if($is){
            $opts['uid']=$uid;
            $opts['big_id']=$big_ids;
            $opts['money']=$money;
            $opts['packetno_end']=$packetno_end;
            $opts['date_ymd']=$ymd;
            $opts['create_time']=time();
            if($order_id!=0){
                $OrderInfo=D("OrderInfo");
                $rrr=$OrderInfo->where("id=".$order_id)->find();
                if(!$rrr){
                    $this->echoJson(array('result' => 1, 'info' => '订单错误'));exit;
                }
                $opts['is_order']=1;
                $opts['content_id']=$order_id;
            }
            $rr=$recharge_order->add($opts);
            if(!$rr){
                $this->echoJson(array('result' => 1, 'info' => "添加失败"));exit;
            }
            $this->echoJson(array('result' => 0, 'info' => $rr));exit;
        }else{
            $this->echoJson(array('result' => 1, 'info' => "系统错误"));exit;
        }
        
    }
    //判断是否支付成功
    public function is_suc(){
        $id=I("request.id");
        $sig=I("request.sig");
        $uid=I("request.uid");
        if($sig!=md5($uid."qb123")){
            $this->echoJson(array('result' => 1, 'info' => "逗比!"));exit;
        }
        $recharge_order=D("RechargeOrder");
        $bigmoney_yhk=D("BigmoneyYhk");
        $BandcardClass=D("BandcardClass");
        $res=$recharge_order->where("id=".$id." and uid=".$uid." and is_status=1")->find();
        if(!$res){
            $this->echoJson(array('result' => 1, 'info' => "error"));exit;
        }
        $rr=$bigmoney_yhk->where("id=".$res['big_id']." and is_status=1")->find();
        if(!$rr){
            $this->echoJson(array('result' => 1, 'info' => "没有此银行卡"));exit;
        }
        $ress=$BandcardClass->where("id=".$rr['cart_class_id'])->find();
        if(!$ress){
            $this->echoJson(array('result' => 1, 'info' => "没有此类"));exit;
        }
        
        $is=$this->is_hz($res['packetno_end'],$ress['hanghao'],$rr['cart_no'],$rr['cart_name'],$res['money']);
        if($is[0]==0){
            $this->echoJson(array('result' => 2, 'info' => "银行还未处理"));exit;
        }elseif($is[0]==1){
            $arr=$this->get_yinhang_hz($is[1],$ress['hanghao'],$rr['cart_no'],$rr['cart_name'],$res['money']);
            if($arr[0]>0){
                $a=base64_decode($arr[1]);
                $array=  explode(",", $a);
                $recharge_order->where("id=".$id." and uid=".$uid)->save(array("receipt_no"=>$is[1],"receipt_val"=>$arr[1],"update_time"=>time()));
                switch ($array[4]) {
                    case "00":
                        //扣款成功
                        if($res['is_order']==1){
                            $OrderInfo=D("OrderInfo");
                            $rrr=$OrderInfo->where("id=".$res['content_id'])->find();
                            if(!$rrr){
                                $this->echoJson(array('result' => 1, 'info' => '订单错误'));exit;
                            }
                            $OrderInfo->where("id=".$res['content_id'])->setField("pay_status",1);
                            //写订单日志
                            $log=D("OrderLog");
                            $logs['money']=$rrr['cn_goods_total_money'];
                            $logs['log']="用户id为".$uid."购买了商品id为".$rrr['goods_ids']."当前的汇率为".$rrr['rate'];
                            $logs['create_time']=$rrr['create_time'];
                            $log->add($logs);
                            
                            //扣款短信
                            $username = '70212023'; 
                            $password = '7dcae6b06b8f784611dea71afe50707e';
        
                            $content="您尾号".substr($rr['cart_no'],-4)."已成功扣款:".$rrr['cn_goods_total_money']."元";
                            $http = 'http://api.duanxin.cm/?action=send&username='.$username.'&password='.$password.'&phone='.$rr['phone'].'&content='.urlencode( iconv('utf-8','gbk',$content) );
                            $ch=curl_init();
                            curl_setopt($ch,CURLOPT_URL,$http);
                            curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
                            curl_exec($ch);
                            curl_close($ch);
                            
                            $this->echoJson(array('result' => 0, 'info' => "付款成功"));exit;
                        }else if($res['is_order']==0){//充值
                            //加到用户账户上并记录充值流水
                            $User=D("User");
                            $User->where("id=".$uid)->setInc("money_available",$array[12]*0.01);
                            $money_logmoney_log=D("MoneyLog");
                            $t=time();
                            $opt['uid']=$uid;
                            $opt['order_no']=  md5($t);
                            $opt['action']="大额充值";
                            $opt['money']=$array[12]*0.01;
                            $opt['time']=$t;
                            $money_logmoney_log->add($opt);
                            
                            //扣款短信
                            $username = '70212023'; 
                            $password = '7dcae6b06b8f784611dea71afe50707e';
        
                            $content="您尾号".substr($rr['cart_no'],-4)."已成功扣款:".($array[12]*0.01)."元";
                            $http = 'http://api.duanxin.cm/?action=send&username='.$username.'&password='.$password.'&phone='.$rr['phone'].'&content='.urlencode( iconv('utf-8','gbk',$content) );
                            $ch=curl_init();
                            curl_setopt($ch,CURLOPT_URL,$http);
                            curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
                            curl_exec($ch);
                            curl_close($ch);
                            
                            $this->echoJson(array('result' => 0, 'info' => "充值成功"));exit;
                        }
                        
                        
                        break;
                    case "01":
                        $this->del_big($id,$res['big_id'],$uid,0,0);
                        $this->echoJson(array('result' => 11, 'info' => "账号不存在"));exit;
                        break;
                    case "02":
                        $this->del_big($id,$res['big_id'],$uid,0,0);
                        $this->echoJson(array('result' => 12, 'info' => "账号户名不符合"));exit;
                        break;
                    case "03":
                        $this->del_big($id,$res['big_id'],$uid,1,0);
                        $this->echoJson(array('result' => 13, 'info' => "银行卡余额不足"));exit;

                        break;
                    case "04":
                        $this->del_big($id,$res['big_id'],$uid,1,0);
                        $this->echoJson(array('result' => 14, 'info' => "今日充值已到限制"));exit;
                        break;  
                    default:
                        $this->del_big($id,$res['big_id'],$uid,0,0);
                        $this->echoJson(array('result' => 15, 'info' => "未知错误"));exit;
                        break;
                }
                
            }else{
                $this->echoJson(array('result' => 1, 'info' => "系统错误"));exit;
            }
            
        }else{
            $this->echoJson(array('result' => 1, 'info' => "参数错误"));exit;
        }
    }
    private function del_big($id,$big_id,$uid,$status,$order_status=1){
        $recharge_order=D("RechargeOrder");
        $bigmoney_yhk=D("BigmoneyYhk");
        $UserBigMoney=D("UserBigmoney");
        $res=$recharge_order->where("id=".$id." and uid=".$uid." and big_id=".$big_id)->save(array("is_status"=>$order_status,"updaet_time"=>time()));

        $rr=$bigmoney_yhk->where("id=".$big_id)->save(array("is_status"=>$status,"updaet_time"=>time()));

        $rrr=$UserBigMoney->where("big_id=".$big_id." and uid=".$uid)->save(array("is_status"=>$status,"updaet_time"=>time()));

        return true;
    }
    //大额支付===============start================
    private function big_money($packetno_end,$hanghao,$cart_no,$cart_name,$money){
        $obj = new \Org\Util\bigmoney();
        $result=$obj->index(1,$packetno_end,$hanghao,$cart_no,$cart_name,$money);
//        print_r($result);
        if($result[0]==1){
            return true;
        }else{
            return false;
        }
    }
    //判断是否有回执
    private function is_hz($packetno_end,$hanghao,$cart_no,$cart_name,$money){
        $obj = new \Org\Util\bigmoney();
        $result=$obj->index(3,$packetno_end,$hanghao,$cart_no,$cart_name,$money);
//        $result=$obj->index(2,'00001','6216910202676810','雷',0.01);
        return $result;
        
    }
    //获取银行回执
    private function get_yinhang_hz($no,$hanghao,$cart_no,$cart_name,$money){
        $obj = new \Org\Util\bigmoney();
        $result=$obj->index(4,$no,$hanghao,$cart_no,$cart_name,$money);
        return $result;
    }
    //大额支付===============end================

    //4元素验证
    public function fouryz(){
        $privite="";//商户秘钥
        $data['xml']='<?xml version="1.0" encoding="UTF-8"?>';
        $data['xml'].= '<message>';  
        $data['xml'].= '<head>';
            $data['xml'].=  '<version>01</version>';
            $data['xml'].=  '<msgType>0002</msgType>';
            $data['xml'].=  '<chanId></chanId>';
            $data['xml'].=  '<merchantNo></merchantNo>';
            $data['xml'].=  '<clientDate></clientDate>';
            $data['xml'].=  '<serverDate></serverDate>';
            $data['xml'].=  '<tranFlow></tranFlow>';
            $data['xml'].=  '<tranCode></tranCode>';
            $data['xml'].=  '<respCode></respCode>';
            $data['xml'].=  '<respMsg></respMsg>';
        $data['xml'].= '</head>';
        $data['xml'].= '<body>';
            $data['xml'].= '<bankCardNo></bankCardNo>';//银行卡号
            $data['xml'].= '<idNum></idNum>';//身份证
            $data['xml'].= '<idName></idName>';//名字
            $data['xml'].= '<prebankmobile></prebankmobile>';//预留手机号
            $data['xml'].= '<terminalType></terminalType>';//请求终端类型
        $data['xml'].= '</body>';
        $data['xml'].= '</message>'; 
        //有字符串则用base64转换
        $data['mac']=  md5($data['xml'].$privite);
        
        //https请求
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1); // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        $tmpInfo = curl_exec($curl); // 执行操作
        curl_close($curl); // 关闭CURL会话
        print_r($tmpInfo); // 返回数据
        
    } 
    
//    public function ttt(){
//        $setting=C('UPLOAD_SITEIMG_QINIU');
//        $setting['driverConfig']['domain']='img.user.ivf-bb.com';
//        $setting['driverConfig']['bucket'] = 'imageuser';
////        $setting['saveName'] = 'asdasd';
//        
//        $setting['subName'] = 'asdasd/'.date('Y-m-d',time());
//        $Upload = new \Think\Upload($setting);
//        $info = $Upload->upload($_FILES);
//        print_r($info);
//    }
    
//    public function testreg(){
//        $user=D('User');
//    	$data['register_time'] = time();
//        for($i=31;$i<=50;$i++){
//            $phone=$i+10000000000;
//            $password=md5($phone);
//            $data['name']='ivfbb'.$phone;
//            $data['password'] = $password;
//            $data['telephone'] = $phone;
//            $user->add($data);
//        }
//        
//    }
}
